当前目录(与java项目同一个目录)下有一个123.txt文件,请编写程序,使程序能够打印出文件中的内容。用Java io字节流方式编写
时间: 2024-03-05 08:53:54 浏览: 14
可以使用Java的FileInputStream和BufferedInputStream类来读取文件内容。具体实现步骤如下:
1. 创建一个FileInputStream对象,指定要读取的文件路径。
2. 创建一个BufferedInputStream对象,将FileInputStream对象作为参数传入。
3. 创建一个byte数组,用于存储读取到的数据。
4. 调用BufferedInputStream对象的read()方法,读取数据到byte数组中。
5. 将byte数组转换成字符串,即为文件的内容。
6. 关闭流。
以下是示例代码实现:
```java
import java.io.*;
public class ReadFileContent {
public static void main(String[] args) {
String filePath = "123.txt"; // 指定要读取的文件路径
File file = new File(filePath);
// 判断文件是否存在
if (!file.exists()) {
System.out.println("文件不存在!");
return;
}
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = bis.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
System.out.println("文件内容为:" + sb.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
需要注意的是,该代码中使用了try-with-resources语句来自动关闭流。如果使用该语句,就不需要在finally块中手动关闭流了。