java文件一行一行读取_java一行一行写入或读取文件
时间: 2023-07-18 20:03:16 浏览: 83
可以使用Java中的FileReader和BufferedReader类来一行一行读取文件,也可以使用FileWriter和BufferedWriter类来一行一行写入文件。
以下是一个例子,演示如何使用FileReader和BufferedReader类一行一行读取文件:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileLineByLine {
public static void main(String[] args) {
File file = new File("file.txt");
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以下是一个例子,演示如何使用FileWriter和BufferedWriter类一行一行写入文件:
```java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileLineByLine {
public static void main(String[] args) {
File file = new File("file.txt");
try (FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String line = "This is a line.";
bufferedWriter.write(line);
bufferedWriter.newLine();
line = "This is another line.";
bufferedWriter.write(line);
bufferedWriter.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请注意,在使用BufferedReader和BufferedWriter时,要记得使用try-with-resources语句块,这样可以确保资源被正确地关闭。
阅读全文