帮我写个java文件通过字节流读取桌面上文本文件中的数据,一定关闭流
时间: 2023-06-06 08:06:00 浏览: 51
好的,这是一个简单的Java代码示例,可以通过字节流读取桌面上的文本文件中的数据并关闭流:
```java
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try {
File file = new File(System.getProperty("user.home") + "/Desktop/file.txt");
InputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
inputStream.read(buffer);
String fileContent = new String(buffer);
System.out.println(fileContent);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,此代码假定文本文件已存在于当前用户的桌面上,并且文件名为“file.txt”。如果文件名和位置不同,请相应更改代码中的路径。