1) 在C盘根目录创建文本文件Hello.txt,并往里写入若干行文本。从Hello.txt中读取文本并显示在屏幕上。使用字符流和字节流两种模式实现。
时间: 2024-02-13 08:00:58 浏览: 85
好的,我来回答你的问题。
使用字符流模式实现:
```java
import java.io.*;
public class CharStreamExample {
public static void main(String[] args) {
try {
// 创建文件对象
File file = new File("C:\\Hello.txt");
// 创建字符输入流
FileReader reader = new FileReader(file);
// 创建字符缓冲区
BufferedReader bufferedReader = new BufferedReader(reader);
// 读取文件内容并输出到屏幕
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// 关闭流
bufferedReader.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
使用字节流模式实现:
```java
import java.io.*;
public class ByteStreamExample {
public static void main(String[] args) {
try {
// 创建文件对象
File file = new File("C:\\Hello.txt");
// 创建字节输入流
FileInputStream inputStream = new FileInputStream(file);
// 创建字节数组缓冲区
byte[] buffer = new byte[1024];
// 读取文件内容并输出到屏幕
int length;
while ((length = inputStream.read(buffer)) != -1) {
System.out.println(new String(buffer, 0, length));
}
// 关闭流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们分别使用了字符流和字节流两种模式实现了从文件中读取文本并显示在屏幕上的功能。其中,字符流模式使用了FileReader和BufferedReader类,字节流模式使用了FileInputStream类。