File four traverse the files and directories in the folder

File files and directories in the specified folder

Two methods

String[] list()

Returns an array of strings naming the files and directories in the directory represented by this abstract pathname.
Demo code:

 private static void demo01() {
    //string[] list()
   File file=new File("E:\\xpu\\ideaproject\\20190905\\src\\cn\\itcast\\File");
   // File file=new File("E:\\xpu\\ideaproject\\20190905\\src\\cn\\itcast\\File\\1.txt");抛出异常
   //File file=new File("E:\\xpu\\ideaproject\\20190905\\src\\cn\\itcast\\Fil");抛出异常
    String[] list = file.list();
    for (String tt:list
         ) {
        System.out.println(tt);
    }

}

Effect:
1.txt
123
2.txt
Demo01File.java
Demo02Filelujing.java
Demo03FileMethods.java
Demo04FilePanduan.java
Demo05Filecreatedelete.java
Demo06FileBianli.java

File[] listFiles()

Returns an array of abstract pathnames, representing the files in the directory represented by the abstract pathname.
These two methods, if the given path does not exist or the given path is not a directory, throw an exception
demo code:

  private static void demo02() {
    File file=new File("E:\\xpu\\ideaproject\\20190905\\src\\cn\\itcast\\File");
    File[] files = file.listFiles();
    for (File fileo:files
         ) {
        System.out.println(fileo);
    }
}
效果:

E:\xpu\ideaproject\20190905\src\cn\itcast\File\1.txt
E:\xpu\ideaproject\20190905\src\cn\itcast\File\123
E:\xpu\ideaproject\20190905\src\cn \itcast\File\2.txt
E:\xpu\ideaproject\20190905\src\cn\itcast\File\Demo01File.java
E:\xpu\ideaproject\20190905\src\cn\itcast\File\Demo02Filelujing.java
E: \xpu\ideaproject\20190905\src\cn\itcast\File\Demo03FileMethods.java
E:\xpu\ideaproject\20190905\src\cn\itcast\File\Demo04FilePanduan.java
E:\xpu\ideaproject\20190905\src\cn \itcast\File\Demo05Filecreatedelete.java
E:\xpu\ideaproject\20190905\src\cn\itcast\File\Demo06FileBianli.java
Note:
1. For these two methods, the given path does not exist or the given path is not one Directory, throw an exception
2. Hidden files and file directories can be obtained as well

Guess you like

Origin blog.csdn.net/tangshuai96/article/details/102750490