-4

I need to know if it's possible to do this:

  • i've some .txt file in a directory in my filesystem
  • i would like to write a java code that does this:

    • Automatically read all the files in the directory
    • Give me a output

Exists some library? or it's just a code problem? It's possible?

Thanks

Alist3r
  • 556
  • 3
  • 11
  • 27
  • 2
    What does automatic mean ? There has to be some trigger right ? – AllTooSir May 23 '14 at 07:38
  • 1
    possible duplicate of [Read all files in a folder](http://stackoverflow.com/questions/1844688/read-all-files-in-a-folder) – akash May 23 '14 at 07:45
  • This specific question was already answered in another thread: http://stackoverflow.com/questions/1844688/read-all-files-in-a-folder – DuKo May 23 '14 at 07:41

2 Answers2

1

Of course it's possible. You need to look at File, Reader classes. A useful method is File#listFiles. Happy coding.

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
1

Reads & prints the content

public static void main(String[] args) {
    List<String> li=new TestClass().textFiles("your Directory");
    for(String s:li){
        try(BufferedReader br = new BufferedReader(new FileReader(s))) {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
            System.out.println(everything);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

For getting all Text files in the Directory

List<String> textFiles(String directory) {
      List<String> textFiles = new ArrayList<String>();
      File dir = new File(directory);
      for (File file : dir.listFiles()) {
        if (file.getName().endsWith((".txt"))) {
          textFiles.add(file.getPath());
        }
      }
      return textFiles;
    }
Ulaga
  • 863
  • 1
  • 8
  • 17