Procesamiento de directorios de archivos

I am writing a program which reads in files and then processes them. At the moment, I am using a BufferedReader to read in a list of files from a txt file. This txt file was generated in a command prompt from doing:

dir > filelist.txt

and then cropping down this to just the filenames.

I can incorporate this into my script by:

//pseudo code(needs further directory specification)
Runtime run = Runtime.getRuntime();//pseudo code(needs further directory specification)
Process process = run.exec("dir > filelist.txt");

This command gives the directory with files in the form:

dd/mm/yyyy hh:mm       (filesize) file

Once I have this file I can run a Regex to extract the filename.

Pattern file = Pattern.compile("(\d){2}/(\d){2}/(\d){4}\s(\d){2}(:)(\d){2}\s(\d+)\s(.+)\.txt");

for (String fileline : filelist) {
    Matcher matchfile = file.matcher(fileline);
    if(matchfile.find()){
        filearray.add(matchfile.group().split("\\s")[3]);
    }
}

Is there an easier way to get just the file names from a directory within Java SE? This seems a bit long winded.

preguntado el 31 de julio de 12 a las 10:07

3 Respuestas

Utilice las list() Método

File f = new File("d:\\MyFolder");
String[] fileNames = f.list();

Puedes seguir separate out the file and directories, using methods like

isFile()
isDirectory()

///////////////////Edited////////////////

Asumir i want to find out whether this File object is a file or a directory...

File f = new File("d:\\MyFolder");

if (f.isDirectory()) {

    System.out.println("Its a directory");
}

Respondido 31 Jul 12, 11:07

Could you clarify your edit to include proper syntax for the two methods? - user1486147

With Java 7 you have the nio.2 tools , more complete and useful with Caminos y archivos clases

Respondido 31 Jul 12, 10:07

Here you can get sample code to get list of files from a folder.

File file = new File("C:/MyFolder/");
    File[] files = file.listFiles();
    for(File f: files){
        System.out.println(f.getName());
    }

You can get more examples from http://java2novice.com/java-file-io-operations/file-list-from-folder/

Respondido 31 Jul 12, 12:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.