I need to read the name of the files contained within a package, for example, read the name file01.txt
, as in the image below:
So I can scroll through the arquivos
package without having to name a file for reading.
You can do with listFiles
or Files.walk of Java 8.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
class Teste {
public static void main(String[] args) {
final File pasta = new File("C:\teste");
listaArquivos(pasta);
listaArquivosJava8(pasta);
}
public static void listaArquivos(final File pasta) {
for (final File fileEntry : pasta.listFiles()) {
if (! fileEntry.isDirectory()) {
System.out.println(fileEntry.getName());
}
}
}
public static void listaArquivosJava8(final File pasta) {
try(Stream<Path> paths = Files.walk(Paths.get(pasta.toURI()))) {
paths.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try the following:
String path = getClass().getResource("arquivos").getPath();
File[] files = new File(path).listFiles();
for(File file : files){
System.out.println(file.getName());
}
Remembering that path
will only be recovered correctly as indicated in the code, taking into account that the arquivos
folder is part of the project. If it's external, you'll need to enter the absolute path, such as the @Joe Torres answer
Look, my friend, it's kind of rusty in java, but as far as I can remember, you can list the files in this way:
File folder = new File("c:\pathproprojeto\src\arquivos");
File[] listOfFiles = folder.listFiles();
public static void getImgs(String path){
File file = new File(path);
File[] arquivos = file.listFiles();
for (File arquivo : arquivos) {
System.out.println(arquivo);
}
}