Java automatically reads all the files in the specified folder

  • 2021-01-25 07:30:39
  • OfStack

The ability to automatically read all files in the folder is very useful when processing or reading data, otherwise you need to manually modify the file path, very troublesome. It's fine if there are only a few files in the folder, but when the number of files is very large, it can lead to a lot of work, and some files may be missing.

Here's how to do it.

java code:


import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.util.ArrayList; 
 
 
public class readFile { 
  private static ArrayList<String> listname = new ArrayList<String>(); 
  public static void main(String[] args)throws Exception{ 
    readAllFile("data/"); 
    System.out.println(listname.size()); 
  } 
  public static void readAllFile(String filepath) { 
    File file= new File(filepath); 
    if(!file.isDirectory()){ 
      listname.add(file.getName()); 
    }else if(file.isDirectory()){ 
      System.out.println(" file "); 
      String[] filelist=file.list(); 
      for(int i = 0;i<filelist.length;i++){ 
        File readfile = new File(filepath); 
        if (!readfile.isDirectory()) { 
          listname.add(readfile.getName()); 
        } else if (readfile.isDirectory()) { 
          readAllFile(filepath + "\\" + filelist[i]);// recursive  
        } 
      } 
    } 
    for(int i = 0;i<listname.size();i++){ 
      System.out.println(listname.get(i)); 
    } 
  } 
} 

Knowledge points involved:

1, File. isDirectory ()

This method is part of the java.io package and is used to check whether the file representing this abstract pathname is a directory. . The following is a java io. File. isDirectory () method statement.


public boolean isDirectory() 

This method returns true if and only if the file representing this abstract pathname is a directory, otherwise it returns false.

2. How to add elements and output to list

Such as:


ArrayList<String> list = new ArrayList<String>(); 
list.add("aaa"); 
list.add("bbb"); 
list.add("ccc"); 
for(int i =0 ; i < list.size(); i ++ ){ 
   system.out.println(list.get(i)); 
} 

3. Recursive functions

Recursive functions, in general, are functions that call themselves...
Such as: n! =n(n-1)!
You define the function f(n)=nf(n-1)
And f(n-1) is a function of this definition. That's recursion, and the purpose of recursion is to simplify the design of the program, to make it easier to read.


Related articles: