2021-05-29 File类

1、文件夹遍历
//1 Files.newDirectoryStream
try (DirectoryStream<Path> dirs = Files.newDirectoryStream(Paths.get(""))) {

			for (Path path:dirs){
				System.out.println(path);
			}

		}catch (Exception e){
			e.printStackTrace();
		}
//2 Files.list
try (Stream<Path> paths = Files.list(Paths.get(""))) {
	// Util.printArr(paths.toArray());//转换为数组

	Iterator<Path> iter = paths.iterator();
	while(iter.hasNext()){
		System.out.println(iter.next());
	}
}catch (Exception e){
	e.printStackTrace();
}
2、遍历目录
/**
	 * 过滤指定路径下以startStr开始,endStr结束的全部文件
	 * @param path
	 * @return
	 */
	public static List<Path> getPathOfAllDirFilterStartEnd(Path path,String startStr,String endStr){
		ArrayList<Path> list = new ArrayList<>();
		try {
			Files.walkFileTree(path,new SimpleFileVisitor<Path>(){
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					if(!(file.startsWith(startStr)&&file.endsWith(endStr))){
						list.add(file);
					}
					return FileVisitResult.CONTINUE;
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;
	}
3、删除文件
Files.deleteIfExists(path);
4、创建文件夹、文件
//可以创建多级子目录
Files.createDirectories(Paths.get("path"));
//创建文件,目录存在才能创建
Files.createFile(Paths.get("path"));
5、StringUtils类

//todo
StringUtils 详解

6、ImageUtils类

//todo

7、文件写入
try {
	OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(new 		        		File("o://useless/stud.txt"),true), "utf-8");
	fout.append("12");
	fout.close();
} catch (Exception e) {
	e.printStackTrace();
}

FileOutputStream: 第一个参数可以是路径字符串,也可以是File对象。第二参数append,默认false,表示是否追加。该类向文件写内容的时候,只以字节流写入。

OutputStreamWriter:第二个参数指定写入编码。以字符流写入。

1.2 管道流写入

//写文件
		try {
			BufferedWriter bw = Files.newBufferedWriter(Paths.get("./test.txt"), StandardCharsets.UTF_8, StandardOpenOption.APPEND);

			bw.write("7\n");
			bw.close();//如果不关闭流,就写不进去!
		} catch (IOException e) {
			e.printStackTrace();
		}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值