0

I want to read file permissions in unix and write the permissions to a csv file. Here is my code:

           static void getFilePermissions(String fileName) {

    try {
        Process proc = Runtime.getRuntime().exec("ls -lrt "+fileName + "| cut -c1-10");
        BufferedReader in = new BufferedReader(new InputStreamReader(
                proc.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    // getRecursiveFiles("/scratch/samaggar/SampleDir");
    getFilePermissions("/scratch/samaggar/SampleDir");
}

It gives me the IOException Kindly suggest.I can't use Java7 which provides built in mechanism.

1
  • 1
    What's the stack trace? (You should also use the version of exec() that takes an array to pass the parameters in.) Commented Feb 26, 2014 at 11:57

2 Answers 2

3

Your problem starts here:

"ls -lrt "+fileName + "| cut -c1-10"

Runtime.exec() does NOT launch a shell, and therefore | is treated as an argument to your ls command. ALso, consider what will happen if the file name has a space in it.

Your second problem: you use Runtime.exec(); don't. Use a ProcessBuilder. It has very nifty methods for output redirections etc etc.

Your third problem: instead of piping through cut, just use Java's string methods to do that; it will be faster (no need to fork() for one).

Finally: have a look at the stat command and its --format option...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your valuable suggestions.I am checking ProcessBuilder.In the meanwhile,I removed the cut command and used Java's string methods.Its working!!
0

The problem is already identified in the earlier answer- piping (|) to cut will not work from Runtime.exec(). Instead create a simple shell script e.g. get_perm.sh and put all your scripting code inside that shell script, then call this script from Runtime.exec(). It should work.

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.