Files类的使用

java nio包中Files类的使用,从jdk1.7引入的,下面是简单使用例子说明。

 

1.判断文件是否存在、拷贝文件

package com.test.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class TestCopyFile {

    public static void main(String[] args) {
        String source = "D:\\freestyle\\SJZT\\ODS\\copytest.txt";
        String dest = "D:\\freestyle\\share_files\\download\\bankStaffInfo\\copytest.txt";

        boolean b1 = new File(source).exists();
        System.out.println("文件是否存在:" + b1);

        /*
         * 判断文件是否存在
         *
         * LinkOption可以不传,它代表的是"链接选项"
         * 这个参数主要用于指示方法在检查文件是否存在时,如何处理符号链接。它是一个特殊的文件,指向另一个文件或目录。
         * 如果不传linkOption则默认是跟踪符号链接的。它检查的不是符号链接文件本身是否存在,而是它所指向的目标是否存在。
         * LinkOption只有一个枚举值:NOFOLLOW_LINKS,表示不跟随符号链接。它只检查给定的路径符号链接文件本身是否存在,而完全不关心它指向什么。
         *
         * 补充:
         * 非符号链接文件:如果你检查的路径不是一个符号链接,而是一个普通文件或目录,那么无论是否传递 LinkOption.NOFOLLOW_LINKS,
         * 结果都是一样的,都是检查该普通文件或目录本身是否存在。
         *
         */
        boolean b2 = Files.exists(Paths.get(source));
        System.out.println("文件是否存在:" + b2);

        boolean success = copy(source, dest);
        System.out.println("文件拷贝结果:" + success);
    }


    /**
     * 拷贝文件
     *
     * @param sourcePath
     * @param destPath
     * @return
     */
    public static boolean copy(String sourcePath, String destPath) {
        try {
            Path source = Paths.get(sourcePath);
            Path destination = Paths.get(destPath);
            Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

上面Files.copy如果目标文件的父路径文件夹不存在时,会报错,优化成如下:

/**
     * 拷贝文件
     *
     * @param sourcePath
     * @param destPath
     * @return
     */
    public static boolean copy(String sourcePath, String destPath) {
        try {
            Path source = Paths.get(sourcePath);
            Path destination = Paths.get(destPath);
            Path parentDestination = destination.getParent();
            if (parentDestination != null && !Files.exists(parentDestination)) {
                Files.createDirectories(parentDestination);
                System.out.println("directory not exist, create:" + parentDestination + " success");
            }

            Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

 

 

 

--

posted on 2025-10-31 16:29  有点懒惰的大青年  阅读(5)  评论(0)    收藏  举报