开发者

Traversing files and directories using Java

开发者 https://www.devze.com 2023-03-24 01:46 出处:网络
I have a small code wich can return the list of files under any directory. What I need to do is get the Directories and Files under the first given directory.

I have a small code wich can return the list of files under any directory.

What I need to do is get the Directories and Files under the first given directory.

This is the code I'm using.

    File dir = new File("C:/myDocument/myFolder");

    String[] children = dir.list();
    if (children == null) {

    } else {
        for (int i=0; i<children.length; i++) {

            String filename = children[i];
            System.out.println(filename);
        }
    }

Another thing is when I select the path from Windows 7, I get this 开发者_如何转开发C:\myFolder\myFolder. If I use this path in Java I get this error Invalide Escape sequence Do I have to change it to C:/myDocument/myFolder to get it work.

Help.

Thanks


Yes, forward slashes are fine. They get normalized to the OS-dependent separator.

What the error tells you is that \m is an invalid escape sequence. Each backward slash tries to escape the following character. So if you need backward slashes in a string, use a double slash: "c:\\myDocuments\\myFolder"

In order to get directories and files, you use .listFiles() and then file.isDirectory() to check if it's a directory.


I use a similar way to clear given folders.

    private static void deleteTree(File file)
    {
      if(file.isDirectory())
      {
        File afile[] = file.listFiles();
         System.out.println("Directory: " + file.getFilename);
         if(afile.length > 0)
         {
            for(int i = 0; i < afile.length; i++)
            {
               if(afile[i].isDirectory())
                  System.out.println("Directory: " + afile[i].getFilename);
                  deleteTree(afile[i]);
               else
                  System.out.println("File: " + afile[i].getFilename);
            }
         }
      } else {
       System.out.println("File: " + file.getFilename);
      }
   }


You can misuse File.list(FilenameFilter) for file traversal, e.g:

// list files in dir
new File(dir).list(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        String file = dir.getAbsolutePath() + File.separator + name;
        System.out.println(file);
        return false;
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消