Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "ls *.c" command in java?

I am trying to print "*.C" files in java

I use the below code

public static void getFileList(){
    try
    {
        String lscmd = "ls *.c";
        Process p=Runtime.getRuntime().exec(lscmd);
        p.waitFor();
        BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line=reader.readLine();
        while(line!=null)
        {
            System.out.println(line);
            line=reader.readLine();
        }
    }
    catch(IOException e1) {
        System.out.println("Pblm found1.");
    }
    catch(InterruptedException e2) {
        System.out.println("Pblm found2.");
    }

    System.out.println("finished.");
}

P.S:- It is working fine for "ls" command.when I am using "*" in any command, all aren't work. need the replacement of "*" in the command in java.

UPDATE

Thanks for your help guys.

Now i need the same result for the comment " ls -d1 $PWD/** "in java. it will list all the directory names with the full path.

Thanks for your time.

like image 308
Querier Avatar asked Mar 24 '13 12:03

Querier


2 Answers

You might find this more reliable:

Path dir = Paths.get("/path/to/directory");

try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.c")) {
    for (Path file : stream) {
        // Do stuff with file
    }
}
like image 155
VGR Avatar answered Nov 13 '22 22:11

VGR


You need to execute a command of the form "bash -c 'ls *.c'" ... because the java exec methods do not understand '*' expansion (globbing). (The "bash -c" form ensures that a shell is used to process the command line.)

However, you can't simply provide the above command as a single String to Runtime.exec(...), because exec also doesn't understand the right way to split acommand string that has quoting in it.

Therefore, to get exec to do the right thing, you need to do something like this:

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

In other words, you need to do the argument splitting by hand ...


It should be noted that this example could also be implemented by using FileMatcher to perform the "globbing" and assemble the argument list from the results. But is complicated if you are going something other than running ls ... and IMO the complexity is not justified.

like image 35
Stephen C Avatar answered Nov 13 '22 22:11

Stephen C