It is very useful to be able to automatically read all files in the folder when processing or reading data, otherwise you need to manually modify the file path, which is very troublesome. It would be fine if there are only a few files in this folder, but once the number of files is very large, it will cause a lot of work and may also miss some files.
Next, let me explain how to implement this process.
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 belongs to the contents of the java.io package and is used to check whether the file representing this abstract pathname is a directory. The following is the declaration of the java.io.File.isDirectory() method.
public boolean isDirectory()
If and only if the file representing this abstract pathname is a directory, the method returns true, otherwise the method returns false.
2. How to add elements and output to list
For example:
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 layman's terms, call themselves...
For example: n!=n(n-1)!
You define the function f(n)=nf(n-1)
And f(n-1) is a function defined by this definition. This is recursion. The purpose of recursion is to simplify programming and make the program easy to read.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.