读取文件夹下的子文件夹的所有文件名,并保存成以子文件命名的txt文件

import java.io.File;    
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
 
public class TakeFilePathAndName {    
    public static void main(String[] args) throws FileNotFoundException{   
        // This is the path where the file's name you want to take.   
        String path = "D:\\10stanford 100";
        File file = new File(path);
        File[] array = file.listFiles();
        String s = null;
        for(int i =0;i< array.length;i++) {
        	  try {
        		  s = "d:\\stanford\\"+array[i].getName()+".txt";
        		  File file1 = new File(s);
	 				file1.createNewFile();
	 			} catch (IOException e) {
	 				// TODO 自动生成的 catch 块
	 				e.printStackTrace();
	 			}	  
        	  getFile(array[i].getPath(),s); //得到根目录下的文件路径
        }
    }      
    private static void getFile(String path,String s) {   
        // get file list where the path has          
        // get the folder list  
    	File file1 = new File(path); 
        File[] array = file1.listFiles(); 
	    try {
	    	FileWriter output = new FileWriter(s);
            for(int i=0;i<array.length;i++){        
	         	if(array[i].isFile()) {		
			    //System.out.println(array[i].getName());
				   output.append(array[i].getName());//添加进去文件(图片)名字
  			    }	  
            }
			output.close();
		   } catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
      }   
    }   

因为一些需要,需要读取文件夹下的子文件夹的所有文件名,并保存成以子文件为名称的文件txt格式


输入:

读取文件夹下的子文件夹的所有文件名,并保存成以子文件命名的txt文件_第1张图片


输出:

读取文件夹下的子文件夹的所有文件名,并保存成以子文件命名的txt文件_第2张图片


读取文件夹下的子文件夹的所有文件名,并保存成以子文件命名的txt文件_第3张图片


你可能感兴趣的:(java)