I want to go through all the files in a folder using java. How can I do it?
I want to go through all the files in a folder using java. How can I do it?
public void listarFicherosPorCarpeta(final File carpeta) {
for (final File ficheroEntrada : carpeta.listFiles()) {
if (ficheroEntrada.isDirectory()) {
listarFicherosPorCarpeta(ficheroEntrada);
} else {
System.out.println(ficheroEntrada.getName());
}
}
}
final File carpeta = new File("/home/usuario/Escritorio");
listarFicherosPorCarpeta(carpeta );
With Java 8 it would work like this:
Files.walk(Paths.get("/home/usuario/Escritorio")).forEach(ruta-> {
if (Files.isRegularFile(ruta)) {
System.out.println(ruta);
}
});
import java.io.File;
import java.util.ArrayList;
import java.util.List;
class Test {
public static void main( String[] args ) {
String path = "d://rererer/";
String[] files = getFiles( path );
if ( files != null ) {
int size = files.length;
for ( int i = 0; i < size; i ++ ) {
System.out.println( files[ i ] );
}
}
}
public static String[] getFiles( String dir_path ) {
String[] arr_res = null;
File f = new File( dir_path );
if ( f.isDirectory( )) {
List<String> res = new ArrayList<>();
File[] arr_content = f.listFiles();
int size = arr_content.length;
for ( int i = 0; i < size; i ++ ) {
if ( arr_content[ i ].isFile( ))
res.add( arr_content[ i ].toString( ));
}
arr_res = res.toArray( new String[ 0 ] );
} else
System.err.println( "¡ Path NO válido !" );
return arr_res;
}
} //class
For the example, just change the value of path in main () to list the files in the directory you want.