Unix计算文件行数的命令 - 来自Java代码

4

我正在尝试使用Java代码从UNIX命令中计算文本文件的行数。

我的代码如下:

String filePath = "/dir1/testFile.txt";

Runtime rt = Runtime.getRuntime();
Process p;
try {
    System.out.println("No: of lines : ");
    findLineCount = "cat " + filePath + " | wc -l";
    p = rt.exec(findLineCount);
    p.waitFor();
} catch (Exception e) {
    //code
}

但是,控制台没有显示任何内容。当我直接执行命令时,它可以正常工作。以上代码可能出了什么问题?


侧面问题 - 为什么你还要调用cat,而不是只使用wc -l filePath - user289086
2
@MichaelT 因为我只想知道行数。使用 wc -l 文件路径 可以返回带有文件名的行数。 - Harbinger
3
虽然我不会说它错了,但你可能会对如何使“wc -l”仅打印行数而不带文件名?感兴趣。当你可以使用cut命令操作一行并获得答案时(链接),通过调用cat读取整个文件并将其塞入管道(在大文件上可能非常昂贵)有些浪费。 - user289086
@MichaelT 谢谢。我一定会研究一下的。 - Harbinger
3个回答

3

我建议您使用ProcessBuilder代替Runtime.exec。您还可以通过向wc传递文件路径来简化命令。请不要吞噬Exception异常。最后,您可以使用ProcessBuilder.inheritIO()(将子进程标准输入/输出的源和目标设置为与当前Java进程相同),如下所示:

String filePath = "/dir1/testFile.txt";
try {
    System.out.println("No: of lines : ");
    ProcessBuilder pb = new ProcessBuilder("wc", "-l", filePath);
    pb.inheritIO();
    Process p = pb.start();
    p.waitFor();
} catch (Exception e) {
    e.printStackTrace();
}

当然,不需要启动新进程来计算Java中的行数会更有效率。也许可以这样实现:
int count = 0;
String filePath = "/dir1/testFile.txt";
try (Scanner sc = new Scanner(new File(filePath));) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        count++;
    }
} catch (Exception e) {
    e.printStackTrace();
}
System.out.printf("No: of lines : %d%n", count);

2

当我直接执行该命令时

我怀疑您并没有“直接”执行它,您可能是在终端中运行它。

您的代码也应该在终端中运行该脚本。

rt.exec(new String[]("bash", "-c", findLineCount});

0

这是我打印行数的方法

public static void main(String[] args) {
        try {
            Runtime run = Runtime.getRuntime();
            String[] env = new String[] { "path=%PATH%;" + "your shell path " }; //path of  cigwin  bin or any similar application. this is needed only for windows  
            Process proc = run.exec(new String[] { "bash.exe", "-c", "wc -l < yourfile" }, env);
             BufferedReader reader = new BufferedReader(new InputStreamReader(        
                     proc.getInputStream()));                                          
                    String s;                                                                
                    while ((s = reader.readLine()) != null) {                                
                      System.out.println("Number of lines " + s);                             
                    }                                           

            proc.waitFor();
            int exitValue = proc.exitValue();
            System.out.println("Status {}" +  exitValue);


        }  catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } 
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接