9

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.

6
  • Is there any specific reason you need to do this with the ls command? Commented Mar 24, 2013 at 12:52
  • 1
    Does getRuntime.exec() in java understands * or not? Commented Mar 24, 2013 at 12:57
  • Yeah... i need to print the file/directory names with full path. so i tried with this example. Commented Mar 24, 2013 at 12:59
  • 2
    @Querier Re: your update: don't do this; don't move goalposts on your question. If your original question was answered, accept that answer, and try to solve your modified problem using the information you've got. Don't drag the people who've answered through writing your whole program. If you get stuck again, open a new question with how far you've got. Commented Mar 24, 2013 at 16:26
  • 1
    Also, in Java SE 7, it seems like you have an API available for globbing file paths: docs.oracle.com/javase/tutorial/essential/io/find.html . Globbing is what you call expanding path patterns (*, ? etc.) in a shell. Commented Mar 24, 2013 at 16:28

6 Answers 6

15

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

Alternatively, you can use public File[] File.listFiles(FilenameFilter filter)

File[] files = dir.listFiles(new FilemaneFilter() {
  public boolean accept(File dir, String name) {
    return name.endsWith(".c");
  }
}

Comments

1

The Java way is to use a FilenameFilter. I adapted a code example from here:

import java.io.File;
import java.io.FilenameFilter;
public class Filter implements FilenameFilter {

  protected String pattern;

  public Filter (String str) {
    pattern = str;
  }

  public boolean accept (File dir, String name) {
    return name.toLowerCase().endsWith(pattern.toLowerCase());
  }

  public static void main (String args[]) {

    Filter nf = new Filter (".c");

    // current directory
    File dir = new File (".");
    String[] strs = dir.list(nf);

    for (int i = 0; i < strs.length; i++) {
      System.out.println (strs[i]);
    }
  }
}

update:

For your update, you could iterate over a new File (".").listFiles(); and issue file.getAbsolutePath() on each file.

Comments

1

One example to list files since Java 7.

import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        Path dir = Paths.get("/your/path/");
        try {
            DirectoryStream<Path> ds = Files.newDirectoryStream(dir, "*.{c}");
            for (Path entry: ds) {
                System.out.println(entry);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Comments

1

The * is expanded by the shell. So to use it to expand a filename as a glob, you would have to call the ls command through a shell, e.g. like this:

String lscmd = " bash -c 'ls *.c' ";

Edit

Good point from @Stephen, about exec failing to split the command. To execute the ls -d1 $PWD/* you can do it like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.