Java执行cat重定向命令失败报错:cat: >: No such file or directory
问题原因
Java的Runtime.getRuntime().exec()不会像Linux Shell那样解析重定向符号>>,它会把>>和目标文件路径直接当成cat命令的参数——也就是要读取的文件名,而cat找不到这些"文件",所以抛出找不到文件的异常。
解决方法
方法一:通过Shell执行完整命令
让Bash来解析整个命令,这样重定向符号就能正常工作。把命令打包成bash -c的参数:
Runtime.getRuntime().exec(new String[]{ "/bin/bash", "-c", "cat FULLPATH/file1.txt FULLPATH/file2.txt >> FULLPATH/merged.txt" });
注意要用字符串数组的形式传参,避免命令拆分出错。
方法二:Java原生处理文件合并(更跨平台)
不依赖Linux的cat命令和Shell重定向,直接用Java的IO流完成文件合并,这种方法在Windows等其他系统也能运行:
import java.io.*; public class FileMerge { public static void main(String[] args) { try (FileWriter writer = new FileWriter("FULLPATH/merged.txt", true); BufferedReader reader1 = new BufferedReader(new FileReader("FULLPATH/file1.txt")); BufferedReader reader2 = new BufferedReader(new FileReader("FULLPATH/file2.txt"))) { String line; // 写入第一个文件内容 while ((line = reader1.readLine()) != null) { writer.write(line + System.lineSeparator()); } // 写入第二个文件内容 while ((line = reader2.readLine()) != null) { writer.write(line + System.lineSeparator()); } } catch (IOException e) { throw new RuntimeException("文件合并失败", e); } } }
内容的提问来源于stack exchange,提问作者codependent
相关产品推荐
相关产品推荐

