Java中Files工具类的使用

Java中Files工具类的使用

1. 介绍

Java NIO Files类(java.nio.file.Files)提供了多种方法来处理文件系统中的文件。比直接使用File文件要方便的多了。

2. 判断文件是否存在

boolean exist = Files.exists(Paths.get(path));
boolean notExist = Files.notExists(Paths.get(path));

3. 删除文件

此方式删除文件或者空文件夹,如果文件夹不为空的情况下会报错

Files.delete(Paths.get(path));
Files.deleteIfExists(Paths.get(path));

4. 创建文件及文件夹

Files.createDirectories(Paths.get(path));
Files.createFile(Paths.get(file));

5. 写文件

List<String> list = new ArrayList<>();
list.add("this is title");
list.add("this is content");
Files.write(Paths.get(path), list, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
Files.write(Paths.get(path), "this is context".getBytes(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);

StandardOpenOption.APPEND 追加写文件
StandardOpenOption.CREATE 如果文件不存在,则创建文件
该方法默认是使用UTF-8的字符集写入

如果JDK不是8而是JDK6,采用流的方式追加写文件

private void appendWriteFile(String file, List<String> list) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "GBK"));
            for (String content : list) {
                writer.write(content);
                writer.newLine();
            }
            writer.flush();
        } catch (Exception e) {
            log.error("追加写文件失败!", e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    log.error("关闭流失败!", e);
                }
            }
        }
    }

6. 读取文件

List<String> list1 = Files.readAllLines(Paths.get("/path/file.txt"), StandardCharsets.UTF_8);
List<String> list2 = Files.readAllLines(Paths.get("/path/file.txt"), Charset.forName("UTF-8"));
List<String> list3 = Files.readAllLines(Paths.get("/path/file.txt"), Charset.defaultCharset());

第二个参数用来指定读取文件的字符集

该方法会将文件中的数据一次性都读取到内存中,如果文件特别大,或者处理的文件内容间没有依赖关系,可以选择一条一条读取并处理。

String file = "/path/file.txt";
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
    BufferedReader br = new BufferedReader(reader);) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception e) {
    e.printStackTrace();
}

7. 递归删除文件及文件夹

使用Files.walk进行递归删除文件夹tmp3及其子文件夹

String path = "D:/tmp1/tmp2/tmp3";
Files.walk(Paths.get(path))
        .sorted(Comparator.reverseOrder())
        .map(Path::toFile)
        .forEach(File::delete);

使用Files.walk进行递归删除文件夹tmp3下的所有文件及文件夹,tmp3不删除

String path = "D:/tmp1/tmp2/tmp3";
Files.walk(Paths.get(path))
        .skip(1)
        .sorted(Comparator.reverseOrder())
        .map(Path::toFile)
        .forEach(File::delete);

使用Files.walkFileTree遍历文件夹进行删除文件夹内的所有文件

String path = "D:/tmp/tmp/0";
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
            // 在访问文件时触发该方法
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                System.out.printf("文件被删除 : %s%n", file);
                return FileVisitResult.CONTINUE;
            }

            // 在访问子目录前触发该方法
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                System.out.printf("正在访问目录 : %s%n", dir);
                return FileVisitResult.CONTINUE;
            }

            // 在访问目录之后触发该方法
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!Paths.get(path).equals(dir)) {
                    Files.delete(dir);
                    System.out.printf("文件夹被删除: %s%n", dir);
                }
                return FileVisitResult.CONTINUE;
            }

            // 在访问失败时触发该方法
            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // 写一些具体的业务逻辑
                return super.visitFileFailed(file, exc);
            }

        }
);

使用Files.walkFileTree遍历文件夹删除整个文件夹

String path = "D:/tmp/tmp/0";
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
            // 在访问文件时触发该方法
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                System.out.printf("文件被删除 : %s%n", file);
                return FileVisitResult.CONTINUE;
            }

            // 在访问子目录前触发该方法
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                System.out.printf("正在访问目录 : %s%n", dir);
                return FileVisitResult.CONTINUE;
            }

            // 在访问目录之后触发该方法
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                System.out.printf("文件夹被删除: %s%n", dir);
                return FileVisitResult.CONTINUE;
            }

            // 在访问失败时触发该方法
            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                // 写一些具体的业务逻辑
                return super.visitFileFailed(file, exc);
            }

        }
);

可以通过Files.walkFileTree很灵活的实现一些对文件或文件夹的操作,例如查找指定大小的文件,包含特殊字符的文件夹或文件等功能。
只要重写SimpleFileVisitor对象的四个方法即可。

  • 5
    点赞
  • 62
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值