文件管理存储之本地存储

package com.guige.base.fileutils;


import com.guige.base.dto.FileBaseDto;

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LocalFileUtil extends FileUtil {
    public Path rootLocation;

    /**
     * 上传路径前缀
     */
    public LocalFileUtil(String rootLocationStr){
        super.setStorageType(FILE_LOCAL);
        super.getLinkConf().put("ROOT_LOCATION",rootLocationStr);
        rootLocation = Paths.get(rootLocationStr);

    }
    // Path[] paths = {
 /*     Paths.get(URI.create("fileutils:///D:/dir/test.txt")), // URI路径
              Paths.get("D:/dir/test.txt"),                     // 正常路径
              Paths.get("D:/dir/../dir/test.txt"),              // 冗余路径
              Paths.get("../dir/test.txt")                      // 相对路径
};*/
    @Override
    public boolean saveFile(String path, String filename, InputStream input, boolean replace_existing) throws IOException {
        if (input==null) {
            throw new IOException("File is empty: " + filename);
        }
        /*if (filename.contains("..")) {
            // 文件路径安全校验
            throw new IOException(
                    "不能将文件保存到相对目录路径中: "
                            + filename);

        }*/
        //将上传的文件保存到指定位置
        if(exists(Paths.get(path,filename).toString())&&replace_existing){

            Files.copy(input, rootLocation.resolve(path).resolve(filename), StandardCopyOption.REPLACE_EXISTING);
        }else{
            Files.createDirectories(rootLocation.resolve(path).resolve(filename));
            Files.copy(input, rootLocation.resolve(path).resolve(filename),StandardCopyOption.REPLACE_EXISTING);
        }

        return true;
    }

    @Override
    public boolean saveFile(String path, String filename, byte[] fileDate,boolean replace_existing) throws IOException {
        InputStream input = new ByteArrayInputStream(fileDate);
        return saveFile(path,filename,input,replace_existing);
    }

    @Override
    public boolean saveFile(String path, String filename, String base64Data,boolean replace_existing) throws IOException {
        byte[] fileDate = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(base64Data);
        return saveFile(path,filename,fileDate,replace_existing);
    }

    @Override
    public boolean saveFile(String path, String filename, File file, boolean replace_existing) throws IOException {
        InputStream input = new FileInputStream(file);
        return saveFile(path,filename,input,replace_existing);
    }

    @Override
    public boolean saveFile(String path, File file,boolean replace_existing) throws IOException {
        InputStream input = new FileInputStream(file);
        return saveFile(path,file.getName(),input,replace_existing);
    }

    @Override
    public boolean saveFile(String path, List<File> files,boolean replace_existing) throws IOException {
        for(File file:files){
            saveFile(path,file,replace_existing);
        }
        return true;
    }

    @Override
    public boolean saveLocalFile(String path, List<String> urls, boolean replace_existing) throws IOException {
        for(String url:urls){
            saveFile(path,new File(url),replace_existing);
        }
        return true;

    }

    @Override
    public InputStream readInputStream(String path, String filename) {
        Path  fileNamePath =rootLocation.resolve(path).resolve(filename);
        InputStream input = null;
        try {
            input = new FileInputStream(fileNamePath.toFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return input;
    }
    @Override
    public FileBaseDto readFileInfo(String path, String filename) throws IOException {
        FileBaseDto fileBaseDto = null;
        try {

            String  pathStr = Paths.get(path,filename).toString();
            pathStr.replace("\\", "/");
            List<FileBaseDto> list =  readFileList(pathStr, false);
            if(list !=null&&list.size()!=0){
                fileBaseDto= list.get(0);
            }

        }catch (Exception e){
            throw new IOException(e.getMessage());
        }
        return fileBaseDto;
    }
    @Override
    public List<FileBaseDto> readFileList(String pathStr, boolean isReadDir) throws IOException{
        Path searchPath =rootLocation.resolve(pathStr);


        List<Path> fileList = new ArrayList<>();
        Files.walkFileTree(searchPath,new SimpleFileVisitor<Path>(){
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) // 访问一个目录前要干啥
                    throws IOException{
                    if(isReadDir) {
                        fileList.add(dir);
                    }
                return super.preVisitDirectory(dir,attrs);
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                fileList.add(file);
                return super.visitFile(file, attrs);
            }
        });


        List<FileBaseDto> fileBaseDtos = new ArrayList<>();
        try {


            if(fileList!=null&&!fileList.isEmpty()){
                for(Path path:fileList){
                    FileBaseDto fileBaseDto = new FileBaseDto();

                    if(Files.isDirectory(path)){
                        fileBaseDto.setContentType("dir");
                    }else {
                        fileBaseDto.setContentType(getContentType(path.getFileName().toString()));
                    }
                    fileBaseDto.setOriginName(path.getFileName().toString());
                    fileBaseDto.setFilePath(path.getParent().toString());
                    fileBaseDto.setFileSize(path.toFile().length());
                    fileBaseDto.setStorageType(0);
                    //System.out.println(objectSummary.getStorageClass());
                    fileBaseDtos.add(fileBaseDto);
                }
            }
            return fileBaseDtos;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("加载文件出现异常"+e.getMessage());
        }

    }


    private void delete(Path deletePath) throws IOException{
        try {
            Files.deleteIfExists(deletePath);
        } catch (DirectoryNotEmptyException e) {
            Files.walkFileTree(deletePath, new SimpleFileVisitor<Path>() {
                @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);
                }
            });
        }
    }
    /**
     * 强制删除文件/文件夹(含不为空的文件夹)<br>
     * @param path
     */
    @Override
    public  boolean delete(String path) throws IOException {
        Path deletePath =rootLocation.resolve(path);
        try {
            Files.deleteIfExists(deletePath);
        } catch (DirectoryNotEmptyException e) {
            Files.walkFileTree(deletePath, new SimpleFileVisitor<Path>() {
                @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);
                }
            });
        }
        return true;
    }
    @Override
    public boolean delete(List<String> paths)  throws IOException{
        for(String path:paths){
            delete(path);
        }
        return true;
    }

    @Override
    public boolean exists(String path) {

        return Files.exists(rootLocation.resolve(path));
    }

    @Override
    public boolean moveTo(String path,  String newPath, boolean replace_existing)throws IOException {
        if(replace_existing){
            operateDir(true,path,newPath,StandardCopyOption.REPLACE_EXISTING);
        }else{
            operateDir(true,path,newPath);
        }
        return true;
    }
    @Override
    public boolean copy(String path,  String newPath, boolean replace_existing) throws IOException{
        if(replace_existing){
            operateDir(false,path,newPath,StandardCopyOption.REPLACE_EXISTING);
        }else{
            operateDir(false,path,newPath);
        }
        return true;
    }
    private void operateDir(boolean move,String path,  String newPath, CopyOption... options) throws IOException{
        if(path.contains(".")&&!newPath.contains(".")){
            throw new IllegalArgumentException("源文件是文件,目标文件是文件夹");
        }else if(!path.contains(".")&&newPath.contains(".")){
            throw new IllegalArgumentException("目标文件是文件,源文件是文件夹");
        }
        Path source =  rootLocation.resolve(path);
        Path target =  rootLocation.resolve(newPath);


        if(null==source) {
            throw new IllegalArgumentException("source must be directory");
        }


        // 目标文件夹不能是源文件夹的子文件夹
        if(isSub(source.toString(),target.toString())){
            throw new IllegalArgumentException("目标文件夹不能是源文件夹的子文件夹");
        }
        // 如果指定了REPLACE_EXISTING选项则不清除目标文件夹
        boolean clear=false;
        for(CopyOption option:options) {
            if (StandardCopyOption.REPLACE_EXISTING == option) {
                clear = true;
                break;
            }
        }
        // 如果指定了REPLACE_EXISTING选项则清除目标文件夹
        if(clear){
            delete(target);
        }
        Files.walkFileTree(source,
                new SimpleFileVisitor<Path>() {

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

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {


                        if(move) {
                            Files.move(file, target.resolve(file.subpath(source.getNameCount(), file.getNameCount())), options);
                        }
                        else {
                            Files.copy(file, target.resolve(file.subpath(source.getNameCount(), file.getNameCount())), options);
                        }
                        return FileVisitResult.CONTINUE;
                    }

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


    public  boolean sameOrSub(String parentStr,String subStr) throws IOException{
        Path parent = rootLocation.resolve(parentStr);
        Path sub = rootLocation.resolve(parentStr);
        if(subStr.contains(rootLocation.toString())){
            sub=rootLocation.resolve(subStr);
        }
        if(parentStr.contains(rootLocation.toString())){
            parent=rootLocation.resolve(parentStr);
        }
        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;
    }


    public  boolean isSub(String parentStr,String subStr) throws IOException{
        Path sub = null;
        if(subStr.contains(rootLocation.toString())){
            sub=rootLocation.resolve(subStr);
        }
        sub=Paths.get(subStr);
        return (null==sub)?false:sameOrSub(parentStr,sub.getParent().toString());
    }



}

猜你喜欢

转载自www.cnblogs.com/songanwei/p/9075138.html