JavaSE_Files

1.Path类;java.nio.file.Path,用于来表示文件路径和文件。

public static Path get(String first, String... more) ;

Path path1 = Paths.get("C:", "aaa/bbb/ccc");
Path path2 = Paths.get("C:/aaa/bbb/ccc");
Path path3 = Paths.get("C:","aaa","bbb","ccc");

2.Files类;java.nio.file.Files,包含一组对文件、目录进行操作的静态方法。

  • 根据path判断文件是否存在
Files.exists(path1);
  • 根据path判断文件是否不存在
Files.notExists(path1);
  • 创建文件
Files.createFiles(path1);
  • 创建目录
Files.createDirectories(path1);
  • 获取字符流
BufferedReader reader = Files.newBufferedReader(path1,Charset.forName("gbk"));
BufferedWrite write = Files.newBufferedWrite(path1);
  • 读取字符文本内容
List<String> lines = Files.readAllines(path1);
List<String> lines = Files.readAllined(Path1,Charset.forName("gbk"));
  • 遍历指定目录
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:"));
DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("C:"),"*.{jpg,png,txt}");
  • 复制文件
Files.copy(path1, System.out);
Files.copy(System.in, path1 ,StandardCopyOption.REPLACE_EXISTING);
Files.copy(path1, Paths.get("C:/datax.txt"),StandardCopyOption.REPLACE_EXISTING);
  • 移动文件
Files.move(path1, Paths.get("C:/temp.txt"),StandardCopyOption.REPLACE_EXISTING);
  • 删除文件
Files.delete(Paths.get("C:/temp.txt"))

3.同过Files类遍历一个文件夹中的所有文件。

  • 使用File类和递归算法进行树遍历。
public class Deam01 {
	public static void main(String[] args) {
		String str = "C:\\Users\\10417\\Desktop\\文件夹\\猿究院";
		File file = new File(str);
		getFiles(file);
	}
	public static void getFiles(File file) {
		File[] files = file.listFiles();
		for (File f : files) {
			if(f.isDirectory()) {
				getFiles(f);
			}else {
				System.out.println(f.getName());
			}
		}
	}
}
  • 使用Files类的walkFileTree方法遍历。
public class Deam02 {
	public static void main(String[] args) {
		String str = "C:\\Users\\10417\\Desktop\\文件夹\\猿究院";
		try {
			//	遍历文件目录树
			//	参数1:根路径Path对象
			//	参数2:文件或目录的访问对象
			Files.walkFileTree(Paths.get(str), new MyFileVisitor());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
//class MyFileVisitor implements FileVisitor<Path>
//SimpleFileVisitor类为FileVisitor的子类;这样不用重写全部的方法。
class MyFileVisitor extends SimpleFileVisitor<Path>{
	//	访问文件
	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
		System.out.println("文件 --> " + file);
		//		继续操作
		return FileVisitResult.CONTINUE;
	}
	//	访问目录
	@Override
	public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
		System.out.println("目录 --> " + dir);
		//		继续操作
		return FileVisitResult.CONTINUE;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值