Java: find files in directory

Asked

Viewed 944 times

-1

I have a simple function to search a file in the application directory and return it, however the return is always being empty, I could not find where the error is.

    Path currentRelativePath = Paths.get(""); 
        String url = currentRelativePath.toAbsolutePath().toString() + "/uploads"; 
        File dir = new File(url);
       //pego o caminho atual e concateno com a pasta que quero, onde está o arquivo txt.

           File[] matches = dir.listFiles(new FilenameFilter()
            {
                public boolean accept(File dir, String name)
                {
                    //return name.startsWith("file") && name.endsWith(".txt");
                    return name.equals("file.txt");

                   //nenhuma das opções de retorno encontra arquivos.
                }
            });

I appreciate contributions.

1 answer

2


In the first return already ok, you just need to iterate on the vector of File[] and take the values, as I did below.

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Path;
import java.nio.file.Paths;


public class getFile {

    public static void main(String[] args) {
        Path currentRelativePath = Paths.get("");
        String url = currentRelativePath.toAbsolutePath().toString() + "/uploads"; 
        File dir = new File(url);
       //pego o caminho atual e concateno com a pasta que quero, onde está o arquivo txt.

        File[] matches = dir.listFiles(new FilenameFilter()
            {
                public boolean accept(File dir, String name)
                {
                    return name.startsWith("file") && name.endsWith(".txt");
                }
            });

        for(File f : matches) {
            System.out.println(f.getAbsolutePath());
        }
    }
}
  • 1

    Hello, put the code in the answer and not the image. This way does not make it easy for other users to test your code.

  • 1

    It worked perfectly, thank you !

Browser other questions tagged

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