Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all text files from one folder using Java?

Tags:

java

file

I need to read all ".txt" files from folder (user needs to select this folder).

Please advise how to do it?

like image 675
DmitryB Avatar asked Jan 19 '12 06:01

DmitryB


People also ask

How do you find all .TXT file in any directory Java?

Assuming you already have the directory, you can do something like this: File directory= new File("user submits directory"); for (File file : directory. listFiles()) { if (FileNameUtils. getExtension(file.

How to read data from all files in a directory using Java?

Core Java bootcamp program with Hands on practiceCreate a file object by passing the required file path as a parameter. Read the contents of each file using Scanner or any other reader. Append the read contents into a StringBuffer. Write the StringBuffer contents into the required output file.

How do you create a directory in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.


2 Answers

you can use filenamefilter class it is pretty simple usage

public static void main(String[] args) throws IOException {

        File f = new File("c:\\mydirectory");

        FilenameFilter textFilter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
            }
        };

        File[] files = f.listFiles(textFilter);
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.print("directory:");
            } else {
                System.out.print("     file:");
            }
            System.out.println(file.getCanonicalPath());
        }

    }

just create an filenamefilter instance an override accept method how you want

like image 162
daemonThread Avatar answered Sep 28 '22 16:09

daemonThread


Assuming you already have the directory, you can do something like this:

File directory= new File("user submits directory");
for (File file : directory.listFiles())
{
   if (FileNameUtils.getExtension(file.getName()).equals("txt"))
   {
       //dom something here.
   }
}

The FileNameUtils.getExtension() can be found here.

Edit: What you seem to want to do is to access the file structure from the web browser. According to this previous SO post, what you want to do is not possible due to security reasons.

like image 42
npinti Avatar answered Sep 28 '22 18:09

npinti