java.lang.Runtime exception “Cannot run program”

后端 未结 2 651
太阳男子
太阳男子 2021-01-24 09:22

I am getting an exception like java.io.IOException: Cannot run program cat /home/talha/* | grep -c TEXT_TO_SEARCH\": error=2, No such file or directory while execut

2条回答
  •  醉梦人生
    2021-01-24 09:41

    Runtime.exec does not use a shell (like, say, /bin/bash); it passes the command directly to the operating system. This means wildcards like * and pipes (|) will not be understood, since cat (like all Unix commands) does not do any parsing of those characters. You need to use something like

    p = new ProcessBuilder("bash", "-c", command).start();
    

    or, if for some bizarre reason you need to stick to using the obsolete Runtime.exec methods:

    p = Runtime.getRuntime().exec(new String[] { "bash", "-c", command });
    

    If you are only running that cat/grep command, you should consider abandoning the use of an external process, since Java code can easily traverse a directory, read lines from each file, and match them against a regular expression:

    Pattern pattern = Pattern.compile("TEXT_TO_SEARCH");
    Charset charset = Charset.defaultCharset();
    
    long count = 0;
    
    try (DirectoryStream dir =
        Files.newDirectoryStream(Paths.get("/home/talha"))) {
    
        for (Path file : dir) {
            count += Files.lines(file, charset).filter(pattern.asPredicate()).count();
        }
    }
    

    Update: To recursively read all files in a tree, use Files.walk:

    try (Stream tree =
        Files.walk(Paths.get("/home/talha")).filter(Files::isReadable)) {
    
        Iterator i = tree.iterator();
        while (i.hasNext()) {
            Path file = i.next();
            try (Stream lines = Files.lines(file, charset)) {
                count += lines.filter(pattern.asPredicate()).count();
            }
        };
    }
    

提交回复
热议问题