The Java implementation reads the file names of all files under the folder including subdirectories
- 2020-04-01 03:56:09
- OfStack
In the process of programming, often used to the file read and write operations. For example, find all the file names under a certain folder.
The following program provides the procedure to obtain the absolute path of all files in a given folder. Can be a certain module, when the need for direct use.
package src;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Vector;
public class FileList {
private String dir_name=null;
private String list_name=null;
private BufferedWriter out = null;
Vector<String> ver=null;
public FileList(String dir_name,String list_name) throws IOException{
this.dir_name=dir_name; //Folder address
this.list_name=list_name; //Save the file address of the file list
ver=new Vector<String>(); //Used as a stack
}
public void getList() throws Exception{
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(list_name, true))); //Writes to the specified file as an append
ver.add(dir_name);
while(ver.size()>0){
File[] files = new File(ver.get(0).toString()).listFiles(); //Gets all the file (folder) names under this folder
ver.remove(0);
int len=files.length;
for(int i=0;i<len;i++){
String tmp=files[i].getAbsolutePath();
if(files[i].isDirectory()) //If it is a directory, join the queue. For subsequent processing
ver.add(tmp);
else
out.write(tmp+"rn"); //If it is a file, output the file name directly to the specified file.
}
}
out.close();
}
}