1

Anyone aware of a method/class/library that will allow me to easily reproduce the results of the *nix ls -l command in Java? Calling ls directly is not an option due to platform independence.

eg. $ls -l myprogram.exe

-rwxrwxrwx 1 auser None 1261568 Nov 15 17:41 C:\myprogram.exe

javacavaj
  • 2,901
  • 5
  • 39
  • 66
  • 4
    To clarify, can you say exactly what part(s) of the 'ls -l' output you need? For example, if you just needed the file size and modification date, then a plain old java.io.File object should do the trick. But if you want the permission information too, you're getting into platform-specific territory there and will require more sophisticated classes. – Jeff Jan 05 '10 at 15:50
  • Excellent point. I'm porting an existing ksh script, so I was hoping to find a method out in the Ether to drop in and use. Absent that I will probably just take what's available in java.io.File. – javacavaj Jan 05 '10 at 16:09

5 Answers5

3

Here is a tutorial on getting a directory listing in java with sample source code.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • 1
    Here is the Javadoc for the File class that is covered the tutorial that Asaph mentions. http://java.sun.com/javase/6/docs/api/ – bkoch Jan 05 '10 at 15:49
2

Here's an implementation of ls -R ~, which lists files recursively starting in the home directory:

import java.io.*;

public class ListDir {

    public static void main(String args[]) {
        File root;
        if (args.length > 0) root = new File(args[0]);
        else root = new File(System.getProperty("user.dir"));
        ls(root); 
    }

    /** iterate recursively */
    private static void ls(File f) { 
        File[] list = f.listFiles();
        for (File file : list) {
            if (file.isDirectory()) ls(file);
            else System.out.println(file);
        }
    }
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

This provides what you are looking for:

ennuikiller
  • 46,381
  • 14
  • 112
  • 137
0

You can use the java.nio.file package.

beggs
  • 4,185
  • 2
  • 30
  • 30
-1

I think we don't have ready to use Java class in java stadard library. But you can develop a tool like *nix ls -l tool by using classes in java.io package.

Upul Bandara
  • 5,973
  • 4
  • 37
  • 60