如何使用BufferedReader和BufferedWriter等缓冲流?
时间: 2023-12-12 11:33:39 浏览: 146
缓冲流的用法
以下是Java中使用BufferedReader和BufferedWriter等缓冲流的示例:
1. 使用BufferedReader从文件中读取数据并打印出来:
```java
import java.io.*;
public class ReadFromFile {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用BufferedWriter向文件中写入数据:
```java
import java.io.*;
public class WriteToFile {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file.txt"));
writer.write("Hello World!");
writer.newLine();
writer.write("This is a test.");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
3. 使用BufferedReader从控制台读取数据并打印出来:
```java
import java.io.*;
public class ReadFromConsole {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line = reader.readLine();
while (!line.equals("exit")) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
4. 使用BufferedWriter向控制台写入数据:
```java
import java.io.*;
public class WriteToConsole {
public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
writer.write("Hello World!");
writer.newLine();
writer.write("This is a test.");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文