How to list the name of the files that are in the directory?

Asked

Viewed 907 times

3

The output of the following method is:

C: Users Desktop User files filename.jpg

How can I get just the filename.jpg in String format? I tried to use FileUtils but as a way out I got this:

����. ELs��/�G������Yos���e�([��E��v���^�C�O���W�ݭ�: Zj 2+ յ v [! J

public static void getImgs(String path){
    File file = new File(path);
    File[] arquivos = file.listFiles();

    try {
        for (File arquivo : arquivos) {
            System.out.println(arquivo);
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
  • 4

    Already tried to print the file name? arquivo.getName(), arquivo.getCanonicalPath(), arquivo.getAbsolutePath()?

1 answer

5


When you use the System.out.println(arquivo); is actually printing the getPath().

follows the documentation

To print the name, try this way:

public static void getImgs(String path){
    File file = new File(path);
    File[] arquivos = file.listFiles();

    try {
        for (File arquivo : arquivos) {
            System.out.println(arquivo.getName());
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
  • Our, fairly simple solution. Different from the found around. Excellent.

  • But it is strange to have as a result in your attempt, @Bruno, that agglomeration of broken characters. This should be the return of getPath()?

  • I didn’t understand why of the characters, but I was using (by recommendation) the Fileutils class to convert File to String and then use split in String to get only the file name. Maybe I was taking the contents of the file and not its path.

  • Just so you know, which operating system are you using?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.