如何将一个文件合并到另一个文件 \Linux
How to merge one file to another \ Linux
我正在尝试使用 Java 程序中的 linux 命令将一个文本文件附加到另一个文本文件。我是 Linux 的新手。我试过排序,它工作得很好,所以我不知道我在使用 'cat' 时做错了什么。
您能否查看我的代码并帮助我找出我做错了什么。
public static void mergeRecords(String fileName, String overflowFileName)
{
String command = "cat " + overflowFileName + " >> " + fileName;
try {
Process r = Runtime.getRuntime().exec(command);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Runtime#exec
不是 shell。
这是一个非常普遍的误解。您需要做的是:
- 使用命令
cat file1 file2
、 创建一个 Process
- 获取该过程的输出,
- 将该输出转储到文件中。
提示:使用 ProcessBuilder
,这将使您的工作更加轻松。
正如其他人所指出的,您不应该使用外部命令来做一些 Java 可以轻松做到的事情:
try (OutputStream existingFile = Files.newOutputStream(
Paths.get(fileName),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND)) {
Files.copy(Paths.get(overflowFileName), existingFile);
}
我正在尝试使用 Java 程序中的 linux 命令将一个文本文件附加到另一个文本文件。我是 Linux 的新手。我试过排序,它工作得很好,所以我不知道我在使用 'cat' 时做错了什么。 您能否查看我的代码并帮助我找出我做错了什么。
public static void mergeRecords(String fileName, String overflowFileName)
{
String command = "cat " + overflowFileName + " >> " + fileName;
try {
Process r = Runtime.getRuntime().exec(command);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Runtime#exec
不是 shell。
这是一个非常普遍的误解。您需要做的是:
- 使用命令
cat file1 file2
、 创建一个 - 获取该过程的输出,
- 将该输出转储到文件中。
Process
提示:使用 ProcessBuilder
,这将使您的工作更加轻松。
正如其他人所指出的,您不应该使用外部命令来做一些 Java 可以轻松做到的事情:
try (OutputStream existingFile = Files.newOutputStream(
Paths.get(fileName),
StandardOpenOption.WRITE,
StandardOpenOption.APPEND)) {
Files.copy(Paths.get(overflowFileName), existingFile);
}