java - 读取和写入txt文件
问题描述
我正在开发一个java程序,其中:
程序读取两个 txt 文件(txt1 和 txt2),然后将 txt1 和 txt2 打印到 txt3,从每个 txt1 和 txt2 交替“行”。
例如:txt1 =
这是第一个
txt2= 那是两个
txt3 应该是:这是第一个是一二
我不确定我错过了什么......任何帮助将不胜感激。
代码:
package combine;
import java.io.*;
import java.util.*;
import java.nio.file.*;
public class Main{
public static void main(String[] args) throws IOException{
String targetDir = "C:\\Parts";
String outputFile = "C:\\Parts\\complete\\TheRavensGreenEggs.txt";
File dir = new File(targetDir);
File[] files = dir.listFiles(new FilenameFilter() {
// Only import "txt" files
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
// Reads all "txt" file lines into a List
List<String> inputFileLines = new ArrayList<>();{
for (File file : files) {
inputFileLines.addAll(Files.readAllLines(Paths.get(file.getAbsolutePath())));
}}
// Writes the List to the console
for (String line : inputFileLines) {
System.out.println(line);
}
// Writes the List to a single "TheRavensGreenEggs.txt" file
Files.write(Paths.get(outputFile), inputFileLines, StandardOpenOption.CREATE);
}}
解决方案
List<String>
像这样使用java.nio
:
public static void main(String[] args) {
// define the input paths and the output path
Path file01Path = Paths.get("Y:\\our\\path\\to\\file_01.txt");
Path file02Path = Paths.get("Y:\\our\\path\\to\\file_02.txt");
Path outputPath = Paths.get("Y:\\our\\path\\to\\result.txt");
// provide a list for the alternating lines
List<String> resultLines = new ArrayList<>();
try {
// read the lines of both files and get them as lists of Strings
List<String> linesOfFile01 = Files.readAllLines(file01Path);
List<String> linesOfFile02 = Files.readAllLines(file02Path);
// find a common border for the iteration: the size of the bigger list
int maxSize = (linesOfFile01.size() >= linesOfFile02.size())
? linesOfFile01.size() : linesOfFile02.size();
// then loop and store the lines (if there are any) in a certain order
for (int i = 0; i < maxSize; i++) {
// lines of file 01 first
if (i < linesOfFile01.size()) {
resultLines.add(linesOfFile01.get(i));
}
// lines of file 02 second
if (i < linesOfFile02.size()) {
resultLines.add(linesOfFile02.get(i));
}
}
// after all, write the content to the result path
Files.write(outputPath,
resultLines,
Charset.defaultCharset(),
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
System.err.println("Some files system operation failed:");
e.printStackTrace();
}
}
推荐阅读
- python - 如何训练模型以及哪种模型最适合此类问题
- javascript - 为什么这个 3 维数组不起作用?
- json - 詹金斯管道 - 找不到文件异常
- r - 在ggplot中移动“组”的所有数据点
- php - 在phonegap上编译为apk时出现jquery登录错误
- flutter - 保存颤振相机图像以供共享
- laravel - 过滤和排序 Laravel 集合
- python - tensorflow,我的 DQN FlappyBird 代理在训练中表现相对较好,但是在我在会话结束后加载训练好的模型后,它很糟糕
- javascript - 为什么在处理 JSON.stringify 时会出现无限递归错误
- google-cloud-storage - 谷歌存储桶和谷歌colab