java 读取某路径下的所有文件,并取出文件名

首先创建一个返回值为List 的getFileList()方法,将路径下的所有 文件放进File[]数组中,然后对判断是否为空,然后接着遍历数组,判断是否为文件夹,若为文件夹则取当前文件的绝对路径,否则将当前文件加入到filelist中 ;

public static List<File> getFileList(String strPath) {

File dir = new File(strPath); File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组 if (files != null) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (files[i].isDirectory()) { // 判断是文件还是文件夹 getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径 } else { String strFileName = files[i].getAbsolutePath(); System.out.println("---" + strFileName); filelist.add(files[i]); } } } return filelist;

}

然后创建一个getFile(List<File>)方法,将fileList中的传入,然后new一个File 对象,然后将filelist中的对象写入到指定路径下的文件中去;

public static void genFile(List<File> nameList) throws Exception{ File file = new File("E:/working/name_list.txt"); FileWriter fw = new FileWriter(file); for(File file1 : nameList) { String temp = file1.getName().replaceAll(".jpg", " "); fw.write(temp); fw.flush(); } fw.close();

}

全部代码如下:

import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class name_list { static List filelist = new ArrayList(); static String strPath = new String("E:\working\zkok"); public static void main(String[] args) throws Exception { // TODO Auto-generated method stub genFile(getFileList(strPath)); } public static List<File> getFileList(String strPath) { File dir = new File(strPath); File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组 if (files != null) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (files[i].isDirectory()) { // 判断是文件还是文件夹 getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径 } else { String strFileName = files[i].getAbsolutePath(); System.out.println("---" + strFileName); filelist.add(files[i]); } } } return filelist; } public static void genFile(List<File> nameList) throws Exception{ File file = new File("E:/working/name_list.txt"); FileWriter fw = new FileWriter(file); for(File file1 : nameList) { String temp = file1.getName().replaceAll(".jpg", " "); fw.write(temp); fw.flush(); } fw.close(); } }

经验分享 程序员 微信小程序 职场和发展