Java遍历一个文件夹下的全部文件

    Java工具中为我们提供了一个用于管理文件系统的类,这个类就是File类,File类与其它流类不同的是,流类关心的是文件的内容。而File类关心的是磁盘上文件的存储。

    一,File类有多个构造器,经常使用的构造器有:

1。public File(String pathname){}

  在pathname路径下创建文件对象

2。public File(String path,String name){}

  在path參数指定的文件夹中创建具有给定名字的File对象。假设path为null,构造器将使用当前文件夹创建对象

3,public File(File dir, String name){}

  File对象dir表示一个文件夹,在dir參数指定的文件夹中创建具有给定名字的File对象,假设dir为null,

构造器将使用当前文件夹创建对象

    二。获得文件的权限属性:

1,表明文件是否可读,可写。可运行

  boolean canRead()

  boolean canWrite()

  boolean canExecute()

2。设置文件的可读。可写,可运行

  boolean setReadable(bollean state,bollean ownerOnly)

  boolean setWritable((bollean state,bollean ownerOnly)

  boolean setExecutable((bollean state,bollean ownerOnly)

3,删除文件

  boolean delete() 

  假设文件被删除则返回true,否则返回false

  void deleteOnExit()

  在虚拟机关闭时将文件删除

4。推断文件是否存在

  boolean exists()

5,获得文件路径名

  String getCanonicalPath()

  返回包括这个文件的规范路径名的字符串该方法会使用恰当的文件夹分隔符,并能够获得底层文件系统所选择的大写和小写处理方式

  String getName()

  返回包括这个File对象的文件名称的字符串。但不包括路径信息

6。推断File为文件还是文件夹

  boolean isDirectory()

  推断是否为一个文件夹

  boolean isFile()

  推断是否为一个文件

7,获得File对象包括的文件名称和文件夹名

  String[] list()

  返回这个File对象包括的文件名称和文件夹名构成的字符创数组

  String[] list(FilenameFilter filter)

  返回有这个File对象包括的满足过滤器条件的文件名称和文件夹名构成的字符串数组

File还有很多方法属性,跟多的能够查看API文档

如今,使用File类来遍历一个文件夹下的全部文件。我的程序过程为:

1,获取pathName的File对象

2,推断该文件或文件夹是否存在。不存在时在控制台输出提醒

3。推断假设不是一个文件夹。就推断是不是一个文件,时文件则输出文件路径

4,获取此文件夹下的全部文件名称与文件夹名的字符串数组

5。假设是一个文件夹。搜索深度currentDepth+1,输出文件夹名后。进行递归

6,假设是文件,则直接输出文件名称


程序例如以下:

import java.io.File;
import java.io.IOException;

public class DirErgodic {

	private static int depth=1;
	
	public static void find(String pathName,int depth) throws IOException{
		int filecount=0;
		//获取pathName的File对象
		File dirFile = new File(pathName);
		//推断该文件或文件夹是否存在。不存在时在控制台输出提醒
		if (!dirFile.exists()) {
			System.out.println("do not exit");
			return ;
		}
		//推断假设不是一个文件夹,就推断是不是一个文件,时文件则输出文件路径
		if (!dirFile.isDirectory()) {
			if (dirFile.isFile()) {
				System.out.println(dirFile.getCanonicalFile());
			}
			return ;
		}
		
		for (int j = 0; j < depth; j++) {
			System.out.print("  ");
		}
		System.out.print("|--");
		System.out.println(dirFile.getName());
		//获取此文件夹下的全部文件名称与文件夹名
		String[] fileList = dirFile.list();
		int currentDepth=depth+1;
		for (int i = 0; i < fileList.length; i++) {
			//遍历文件文件夹
			String string = fileList[i];
			//File("documentName","fileName")是File的还有一个构造器
			File file = new File(dirFile.getPath(),string);
			String name = file.getName();
			//假设是一个文件夹。搜索深度depth++,输出文件夹名后。进行递归
			if (file.isDirectory()) {
				//递归
				find(file.getCanonicalPath(),currentDepth);
			}else{
				//假设是文件,则直接输出文件名称
				for (int j = 0; j < currentDepth; j++) {
					System.out.print("   ");
				}
				System.out.print("|--");
				System.out.println(name);
				
			}
		}
	}
	
	public static void main(String[] args) throws IOException{
		find("D:\MongoDB", depth);
	}
}

測试截图:






原文地址:https://www.cnblogs.com/lxjshuju/p/7107192.html