java依次写入文件
时间: 2024-01-29 12:10:40 浏览: 75
java 按顺序创建文件
5星 · 资源好评率100%
以下是Java依次写入文件的两种方法:
1. 使用BufferedWriter类逐行写入文件:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class WriteToFile {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("hello");
arrayList.add("java");
arrayList.add("hello");
arrayList.add("world");
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:\\itcast\\List.txt"));
for (String s : arrayList) {
bufferedWriter.write(s);
bufferedWriter.newLine();
bufferedWriter.flush();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. 使用PrintWriter类逐行写入文件:
```java
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public class WriteToFile {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("hello");
arrayList.add("java");
arrayList.add("hello");
arrayList.add("world");
try {
PrintWriter printWriter = new PrintWriter(new FileWriter("D:\\itcast\\List.txt"));
for (String s : arrayList) {
printWriter.println(s);
}
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
阅读全文