java导出多个txt
时间: 2023-08-28 16:03:41 浏览: 39
您可以使用 Java 的文件操作 API 来实现导出多个 txt 文件,具体步骤如下:
1. 创建一个包含多个字符串的 List,每个字符串代表一个 txt 文件的内容。
2. 使用 for 循环遍历该 List,依次将每个字符串写入到一个新的 txt 文件中。
具体代码如下:
```java
import java.io.*;
import java.util.*;
public class ExportMultipleTxt {
public static void main(String[] args) {
List<String> txtContentList = new ArrayList<>();
txtContentList.add("This is the content of the first txt file.");
txtContentList.add("This is the content of the second txt file.");
txtContentList.add("This is the content of the third txt file.");
for (int i = 0; i < txtContentList.size(); i++) {
String fileName = "file" + i + ".txt";
String content = txtContentList.get(i);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
上述代码中,我们首先创建了一个包含三个字符串的 List,每个字符串代表一个 txt 文件的内容。然后使用 for 循环遍历该 List,依次将每个字符串写入到一个新的 txt 文件中。在写入文件时,我们使用了 Java 的 try-with-resources 语句,以确保文件流正确关闭。最后运行该程序,即可在当前目录下生成三个 txt 文件,分别命名为 file0.txt、file1.txt 和 file2.txt。