有没有办法将多个文件合并在一起?例如
文件1:
1 A
2 B
3 C
文件2:
4 D
5 E
6 F
合并输出
1 A 4 D
2 B 5 E
3 C 6 F
答案 0 :(得分:0)
相邻合并文件的算法基本上是:
以下是我使用Java 7实现该算法的方法:
import static java.nio.file.StandardOpenOption.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class MergeFiles {
public static void main(String[] args) throws IOException {
// READ file1 into lines1 & file2 into lines2
final Charset CS = Charset.defaultCharset(); // e.g. UTF-8
List<String> lines1 = Files.readAllLines(Paths.get("file1"), CS),
lines2 = Files.readAllLines(Paths.get("file2"), CS);
// MERGE until end of either list, then APPEND until end of lines2
for (int i = 0; i < lines2.size(); i++)
if (i < lines1.size())
lines1.set(i, lines1.get(i) + " " + lines2.get(i));
else
lines1.add(lines2.get(i));
// WRITE lines1 (the merged lines) to some file3
Files.write(Paths.get("file3"), lines1, CS,
CREATE, WRITE, TRUNCATE_EXISTING);
}
}