一些文件操作的代码(主要为java nio)

记录一下一些 Files 的文件操作方式,Files 的具体使用方式可查看 官方文档 :https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html

以下代码复制一下,并修改包路径,执行main 函数,即可看到文件操作效果

package com.example.demotest.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件操作测试类 (官方文档: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html)
 *
 * @date 2021/12/29 15:48
 */

public class FileTest {

    private static void deleteDirTree(String dirPath) throws IOException {
        List<Path> pathList = Files.walk(Paths.get(dirPath)).collect(Collectors.toList());
        Collections.reverse(pathList);
        pathList.forEach(item -> {
            try {
                Files.delete(item);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    private static void ioRead(String filePath) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));

        String s;
        while ((s = bufferedReader.readLine()) != null) {
            System.out.println(s);
        }

        bufferedReader.close();
    }

    private static void ioWrite(String filePath, List<String> stringList, boolean append) throws IOException {
        FileWriter fileWriter = new FileWriter(filePath, append);
        for (String s : stringList) {
            fileWriter.write(s + "\n");
        }
        fileWriter.close();

//        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath, append));
//        for (String s : stringList) {
//            bufferedWriter.write(s);
//            bufferedWriter.newLine();
//        }
//        bufferedWriter.close();
    }

    private static void nioRead(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (Files.isReadable(path)) {
            Files.lines(path).forEach(System.out::println);
        }
    }

    private static void nioWrite(String filePath, List<String> stringList, boolean append) throws IOException {
        StandardOpenOption openOption = StandardOpenOption.TRUNCATE_EXISTING;
        if (append) {
            openOption = StandardOpenOption.APPEND;
        }

        Path path = Paths.get(filePath);
        if (Files.isWritable(path)) {
            Files.write(path, stringList, openOption);
        }
    }

    private static void moveFile(String targetDir, String sourceDir, String fileName, String suffix) throws IOException {
        Path tDir = Paths.get(targetDir);
        Path sourcePath = Paths.get(sourceDir + "/" + fileName + "." + suffix);
        Path targetPath = Paths.get(targetDir + "/" + fileName + "." + suffix);
        if (Files.notExists(tDir)) {
            Files.createDirectories(tDir);
        }
        Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
    }

    private static void getFileInfo(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        if (Files.notExists(path)) {
            return;
        }
        System.out.println("file store: " + Files.getFileStore(path));
        System.out.println("file size: " + Files.size(path));
        System.out.println("last modified time: " + Files.getLastModifiedTime(path));
        System.out.println("owner: " + Files.getOwner(path));
        System.out.println("content type: " + Files.probeContentType(path));

        System.out.println("全部 basic-file-attributes: " + Files.readAttributes(path, "*"));
    }

    private static void createFile(String dirPath, String fileName, String suffix) throws IOException {
        Path dir = Paths.get(dirPath);
        if (Files.notExists(dir)) {
            Files.createDirectories(dir);
        }
        Path filePath = Paths.get(dirPath + "/" + fileName + "." + suffix);
        if (Files.notExists(filePath)) {
            Files.createFile(filePath);
        }
    }

    private static void createDir(String path) throws IOException {
        Path dirPath = Paths.get(path);
        Files.createDirectories(dirPath);
    }

    public static void main(String[] args) throws IOException {
        // 包路径
        String packagePath = "src/main/java/com/example/demotest/test/";

        // 创建目录
        String dir = packagePath + "testFile/";
        createDir(dir);

        // 创建文件
        String path = dir + "/testFile.txt";
        String fileName = "testFile";
        String suffix = "txt";
        createFile(dir, fileName, suffix);

        // 查看部分文件信息
        getFileInfo(path);

        // 移动文件 (同名覆盖)
        String targetDir = packagePath + "moveDir/";
        moveFile(targetDir, dir, fileName, suffix);

        // 查看指定目录下文件
        System.out.println("\nlist moveDir:");
        Files.newDirectoryStream(Paths.get(targetDir))
                .forEach(System.out::println);

        // 再移回来
        moveFile(dir, targetDir, fileName, suffix);

        // 读写操作
        boolean append = false;

        nioWrite(path, Arrays.asList("nio第一行", "nio第二行", "nio第三行"), append);
        System.out.println("=================================");
        nioRead(path);

        ioWrite(path, Arrays.asList("io第一行", "io第二行", "io第三行"), append);
        System.out.println("=================================");
        ioRead(path);

        // 删除所有测试文件及目录
        deleteDirTree(targetDir);
        deleteDirTree(dir);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值