Java - Read all .txt files in folder

2020-02-02 18:23发布

Let's say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I use Java and the BufferReader to read all of the .txt files in folder maps (if it is at all possible)?

7条回答
够拽才男人
2楼-- · 2020-02-02 19:17

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);
            }
        }
    }

}
查看更多
登录 后发表回答