InputStream inputStream = file.getInputStream();如何读取文件内容
时间: 2024-10-30 12:05:47 浏览: 117
当你通过`file.getInputStream()`获取到`InputStream`实例后,通常会配合`BufferedReader`或`DataInputStream`等来逐块读取文件内容,这里给出一个基础示例:
```java
File file = new File("path_to_your_file");
InputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024]; // 每次读取的数据大小
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) { // 当read返回-1表示文件结束
String readContent = new String(buffer, 0, bytesRead); // 转换为字符串
System.out.println(readContent);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
```
在这个例子中,我们创建了一个`BufferedInputStream`来提高效率,然后每次从`inputStream`读取一个固定的字节数,并转换成字符串打印出来。
阅读全文
相关推荐















