使用于NIO实现文件夹的复制/移动,删除

简介: 使用于NIO实现文件夹的复制/移动,删除

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.file.CopyOption;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

public class NioFileUtil {
    
    private static final Logger logger=Logger.getLogger(NioFileUtil.class);
    
    /**
     * 复制文件夹
     * @param source
     * @param target
     * @param options
     * @throws IOException
     * @see {@link #operateDir(boolean, Path, Path, CopyOption...)}
     */
    public static void copyDir(Path source, Path target, CopyOption... options) throws IOException{
        operateDir(false, source, target, options);
    }
    /**
     * 移动文件夹
     * @param source
     * @param target
     * @param options
     * @throws IOException
     * @see {@link #operateDir(boolean, Path, Path, CopyOption...)}
     */
    public static void moveDir(Path source, Path target, CopyOption... options) throws IOException{
        operateDir(true, source, target, options);
    }
    /**
     * 复制/移动文件夹
     * @param move 操作标记,为true时移动文件夹,否则为复制
     * @param source 要复制/移动的源文件夹
     * @param target 源文件夹要复制/移动到的目标文件夹
     * @param options 文件复制选项 
     * @throws IOException
     * @see Files#move(Path, Path, CopyOption...)
     * @see Files#copy(Path, Path, CopyOption...)
     * @see Files#walkFileTree(Path, java.nio.file.FileVisitor)
     */
    public static void operateDir(final boolean move,final Path source, Path target, final CopyOption... options) throws IOException{
        if(null==source||!Files.isDirectory(source))
            throw new IllegalArgumentException("source must be directory");
        final Path dest = target.resolve(source.getFileName());
        // 如果相同则返回
        if(Files.exists(dest)&&Files.isSameFile(source, dest))return;
        // 目标文件夹不能是源文件夹的子文件夹
        // isSub方法实现参见另一篇博客 http://blog.csdn.net/10km/article/details/54425614
        if(isSub(source,dest))
            throw new IllegalArgumentException("dest must not  be sub directory of source");
        boolean clear=true;     
        for(CopyOption option:options)
            if(StandardCopyOption.REPLACE_EXISTING==option){
                clear=false;
                break;
            }
        // 如果指定了REPLACE_EXISTING选项则不清除目标文件夹
        if(clear)
            deleteIfExists(dest);
        Files.walkFileTree(source, 
                new SimpleFileVisitor() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                        // 在目标文件夹中创建dir对应的子文件夹
                        Path subDir = 0==dir.compareTo(source)?dest:dest.resolve(dir.subpath(source.getNameCount(), dir.getNameCount()));
                        Files.createDirectories(subDir);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if(move)
                            Files.move(file, dest.resolve(file.subpath(source.getNameCount(), file.getNameCount())),options);
                        else
                            Files.copy(file, dest.resolve(file.subpath(source.getNameCount(), file.getNameCount())),options);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        // 移动操作时删除源文件夹
                        if(move)
                            Files.delete(dir);
                        return super.postVisitDirectory(dir, exc);
                    }
                });
    }

    /**
     * 强制删除文件/文件夹(含不为空的文件夹)

     * @param dir
     * @throws IOException
     * @see Files#deleteIfExists(Path)
     * @see Files#walkFileTree(Path, java.nio.file.FileVisitor)
     */
    public static void deleteIfExists(Path dir) throws IOException {
        try {
            Files.deleteIfExists(dir);
        } catch (DirectoryNotEmptyException e) {
            Files.walkFileTree(dir, new SimpleFileVisitor() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);
                    return super.postVisitDirectory(dir, exc);
                }
            });
        }
    }

    /**
     * 判断sub是否与parent相等或在其之下

     * parent必须存在,且必须是directory,否则抛出{@link IllegalArgumentException}
     * @param parent 
     * @param sub
     * @return
     * @throws IOException 
     */
    public static boolean sameOrSub(Path parent,Path sub) throws IOException{
        if(null==parent)
            throw new NullPointerException("parent is null");
        if(!Files.exists(parent)||!Files.isDirectory(parent))
            throw new IllegalArgumentException(String.format("the parent not exist or not directory %s",parent));
        while(null!=sub) {
            if(Files.exists(sub)&&Files.isSameFile(parent, sub))
                return true;
            sub=sub.getParent();
        }
        return false;   
    }
    /**
     * 判断sub是否在parent之下的文件或子文件夹

     * parent必须存在,且必须是directory,否则抛出{@link IllegalArgumentException}
     * @param parent
     * @param sub
     * @return
     * @throws IOException
     * @see {@link #sameOrSub(Path, Path)}
     */
    public static boolean isSub(Path parent,Path sub) throws IOException{
        return (null==sub)?false:sameOrSub(parent,sub.getParent());
    }
    
    /**获取路径的完整地址
     * @param subPaths
     * @return
     * @throws Exception
     */
    public static String fileAbsolutePath(String...subPaths) throws Exception{
        if(null == subPaths || subPaths.length == 0){
            throw new Exception("路径不能为空");
        }
        
        StringBuffer buffer=new StringBuffer();
        
        for(int i=0;i<subPaths.length;i++){
            
            String subPath=subPaths[i];
            if(StringUtils.isEmpty(subPath)){
                continue;
            }
            if(i != 0){
                subPath=subPath.replaceFirst("^(?:\\|/)*", "");
            }
            subPath=subPath.replaceFirst("(?:\\|/)*$", "");
            buffer.append(subPath).append("/");
        }
        buffer.deleteCharAt(buffer.length()-1);
        
        String path=buffer.toString();
        
        String absolutePath=new File(path).getAbsolutePath();
        return absolutePath;
    }
    
    /**读取文件内容
     * @param path
     * @return
     * @throws Exception
     */
    public static String readFileContent(String path) throws Exception{
        File file=new File(path);
        if(!file.exists()){
            throw new Exception(StringUtil.format("文件 {} 不存在,无法获取内容",path));
        }else if(!file.isFile()){
            throw new Exception(StringUtil.format("文件 {} 不是文件,无法获取内容", path));
        }else if(!file.canRead()){
            throw new Exception(StringUtil.format("文件 {} 没有读取权限", path));
        }
        
        StringBuffer buffer=new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String tempString = null;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                buffer.append(tempString);
                buffer.append("\n");
            }
        } catch (IOException e) {
            logger.error(StringUtil.format("文件 {} 读取内容失败,{}", path,e.getMessage()));
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        
        return buffer.toString();
    }
    
    /**读取文件内容写入输出流中
     * @param outputStream
     * @throws Exception
     */
    public static void readFileToOutputStream(String path,OutputStream outputStream) throws Exception{
        File file=new File(path);
        if(!file.exists()){
            throw new Exception(StringUtil.format("文件 {} 不存在,无法获取内容",path));
        }else if(!file.isFile()){
            throw new Exception(StringUtil.format("文件 {} 不是文件,无法获取内容", path));
        }else if(!file.canRead()){
            throw new Exception(StringUtil.format("文件 {} 没有读取权限", path));
        }
        
        byte[] b=new byte[1024];
        InputStream inputStream=null;
        int bCount=0;
        try{
            inputStream=new FileInputStream(file);
            
            while((bCount=inputStream.read(b))>0){
                outputStream.write(b, 0, bCount);
            }
            
        }catch(Exception e){
            logger.error(StringUtil.format("读取文件 {} 时出错,{}", path,e.getMessage()));
            throw e;
        }finally{
            if(null != inputStream){
                inputStream.close();
            }
        }
    }
    
    /**保存文件内容
     * @param path
     * @param fileContent
     * @param cover
     * @throws Exception
     */
    public static void saveFileContent(String path,String fileContent,boolean cover) throws Exception{
        File file=new File(path);
        if(!file.exists()){
            throw new Exception(StringUtil.format("文件 {} 不存在,无法获取内容",path));
        }else if(!file.isFile()){
            throw new Exception(StringUtil.format("文件 {} 不是文件,无法获取内容", path));
        }else if(!file.canRead()){
            throw new Exception(StringUtil.format("文件 {} 没有读取权限", path));
        }
        
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,!cover),"UTF-8"));
            
            writer.write(fileContent);
        } catch (IOException e) {
            logger.error(StringUtil.format("文件 {} 写入内容失败,{}", path,e.getMessage()));
            throw e;
        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e1) {
                }
            }
        }
    }
    
    /**路径是否存在
     * @param path
     * @return
     * @throws Exception
     */
    public static boolean fileExists(String path,boolean dir) throws Exception{
        File file=new File(path);
        if(!file.exists()){
            return false;
        }
        if(dir){
            if(!file.isDirectory()){
                throw new Exception(StringUtil.format("路径 {} 不是文件夹", path));
            }
        }else{
            if(!file.isFile()){
                throw new Exception(StringUtil.format("路径 {} 不是文件", path));
            }
        }
        return true;
    }
    
}

相关文章
|
2月前
|
人工智能 Linux API
Magpie, 轻量本地AI网关!免费Token用不完!
Magpie 是开源AI编程模型调度网关,上线一月获1.8万Star。它通过本地高性能网关统一托管多平台API密钥、账号与免费额度,实现跨Agent的模型秒级切换、静默额度轮换与资源复用,显著降低碎片化管理成本。(239字)
Magpie, 轻量本地AI网关!免费Token用不完!
|
网络安全 数据安全/隐私保护
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
用smtp发送邮件,语法错误,无法识别命令。 服务器响应为:Authentication is re
1265 0
|
JSON fastjson 数据格式
利用fastjson对json转map的操作
String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}"; //第一种方式 Map maps = (Map)JSON.
13927 1
|
人工智能 自然语言处理 测试技术
🧠 用 AI 提升你的编程效率 —— 在 PyCharm 中体验通义灵码
通义灵码是一款基于大模型的智能编程辅助工具,现已上线PyCharm插件V2.5+版本。它能根据自然语言描述、注释或上下文生成高质量代码,支持多语言(Python、Java等),提供代码补全、优化建议、单元测试生成及异常排查等功能。集成魔搭MCP市场3000+服务,具备编程智能体模式与长期记忆能力,助开发者提升效率。适用初学者、资深开发者及团队协作场景。小红书、B站、抖音、微博均有相关资源分享。 小红书: http://xhslink.com/a/SvabuxSObf3db bilibili:https://b23.tv/1HJAdIx 抖音: https://v.douyin.com/1DAG
9798 6
|
人工智能 机器人 API
阿里云百炼xWaytoAGI共学课 DAY2 - 更好用的文本知识库应用跟学,快速上手阿里云百炼
本课程是阿里云百炼平台的第二天课程内容,旨在帮助用户了解如何通过阿里云百炼构建和发布自己的AI应用。介绍了如何利用大模型和智能体应用来创建具备强大语言理解和生成能力的AI助手,并通过不同的渠道(如网站、钉钉、微信公众号等)发布这些应用。
3328 8
|
安全 Java
java BigDecimal 的赋值一个常量
在 Java 中,`BigDecimal` 是一个用于精确计算的类,特别适合处理需要高精度和小数点运算的场景。如果你需要给 `BigDecimal` 赋值一个常量,可以使用其静态方法 `valueOf` 或者直接通过字符串构造函数。 以下是几种常见的方法来给 `BigDecimal` 赋值一个常量: ### 使用 `BigDecimal.valueOf` 这是推荐的方式,因为它可以避免潜在的精度问题。 ```java import java.math.BigDecimal; public class BigDecimalExample { public static void
634 4
|
人工智能 自然语言处理 Java
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
文章介绍了Spring AI,这是Spring团队开发的新组件,旨在为Java开发者提供易于集成的人工智能API,包括机器学习、自然语言处理和图像识别等功能,并通过实际代码示例展示了如何快速集成和使用这些AI技术。
14298 4
Spring AI,Spring团队开发的新组件,Java工程师快来一起体验吧
|
Java
java中驼峰命名和下划线命名互转方法(代码实现)
1 /** 2 * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。 3 * 例如:HelloWorld->HELLO_WORLD 4 * @param name 转换前的驼峰式命名的字符串 5 * @return 转换后下划线大写方...
8540 0
|
Linux
Linux中grep命令详解与实战应用
Linux中grep命令详解与实战应用
3121 0
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8058 2