Java - Read all .txt files in folder

旧巷老猫 提交于 2019-11-28 06:25:43
Andrew White

Something like the following should get you going, note that I use apache commons FileUtils instead of messing with buffers and streams for simplicity...

File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();

for (int i = 0; i < listOfFiles.length; i++) {
  File file = listOfFiles[i];
  if (file.isFile() && file.getName().endsWith(".txt")) {
    String content = FileUtils.readFileToString(file);
    /* do somthing with content */
  } 
}
MByD

I would take @Andrew White answer (+1 BTW) one step further, and suggest you would use FileNameFilter to list only relevant files:

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

File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles(filter);

for (int i = 0; i < listOfFiles.length; i++) {
    File file = listOfFiles[i];
    String content = FileUtils.readFileToString(file);
    // do something with the file
}
    final File folder = new File("C:/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/somefile");
    for (final File fileEntry : folder.listFiles()) {
           System.out.println("FileEntry Directory "+fileEntry);

I think it's good way to read all .txt files from maps and sub folder's

 private static void addfiles (File input,ArrayList<File> files)
{
    if(input.isDirectory())
    {
        ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
        for(int i=0 ; i<path.size();++i)
        {
            if(path.get(i).isDirectory())
            {
                addfiles(path.get(i),files);
            }
            if(path.get(i).isFile())
            {
                String name=(path.get(i)).getName();
                if(name.lastIndexOf('.')>0)
                {
                    int lastIndex = name.lastIndexOf('.');
                    String str = name.substring(lastIndex);
                    if(str.equals(".txt"))
                    {
                        files.add(path.get(i));
                    }
                }
            }
        }
    }
    if(input.isFile())
    {
        String name=(input.getName());
        if(name.lastIndexOf('.')>0)
        {
            int lastIndex = name.lastIndexOf('.');
            String str = name.substring(lastIndex);
            if(str.equals(".txt"))
            {
                files.add(input);
            }
        }
    }

}

If you want a better way of doing this using the new java.nio api, then this is the way, taken from the java docs

Path dir = ...;
try (DirectoryStream<Path> stream =
     Files.newDirectoryStream(dir, "*.txt")) {
    for (Path entry: stream) {
        System.out.println(entry.getFileName());
    }
} catch (IOException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can // only be thrown by newDirectoryStream.
    System.err.println(x);
}

Using only JDK, If all your files are in one directory:

File dir = new File("path/to/files/");

for (File file : dir.listFiles()) {
    Scanner s = new Scanner(file);
    // do something with file
    s.close();
}

To exclude files, you can use listFiles(FileFilter)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!