Java檔案操作工具類FileUtils

學習達人的日記本發表於2018-01-26
package com.suobei.xinzhiying.base.utils.file;

import com.suobei.xinzhiying.base.result.ResponseMap;
import com.suobei.xinzhiying.base.utils.aliyun.AliOssUtils;
import com.suobei.xinzhiying.base.utils.commons.CommonUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

    /*判斷檔案是否存在*/
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /*判斷是否是資料夾*/
    public static boolean isDir(String path) {
        File file = new File(path);
        if(file.exists()){
            return file.isDirectory();
        }else{
            return false;
        }
    }

    /**
     * 檔案或者目錄重新命名
     * @param oldFilePath 舊檔案路徑
     * @param newName 新的檔名,可以是單個檔名和絕對路徑
     * @return
     */
    public static boolean renameTo(String oldFilePath, String newName) {
        try {
            File oldFile = new File(oldFilePath);
            //若檔案存在
            if(oldFile.exists()){
                //判斷是全路徑還是檔名
                if (newName.indexOf("/") < 0 && newName.indexOf("\\") < 0){
                    //單檔名,判斷是windows還是Linux系統
                    String absolutePath = oldFile.getAbsolutePath();
                    if(newName.indexOf("/") > 0){
                        //Linux系統
                        newName = absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1)  + newName;
                    }else{
                        newName = absolutePath.substring(0, absolutePath.lastIndexOf("\\") + 1)  + newName;
                    }
                }
                File file = new File(newName);
                //判斷重新命名後的檔案是否存在
                if(file.exists()){
                    System.out.println("該檔案已存在,不能重新命名");
                }else{
                    //不存在,重新命名
                    return oldFile.renameTo(file);
                }
            }else {
                System.out.println("原該檔案不存在,不能重新命名");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /*檔案拷貝操作*/
    public static void copy(String sourceFile, String targetFile) {
        File source = new File(sourceFile);
        File target = new File(targetFile);
        target.getParentFile().mkdirs();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fis = new FileInputStream(source);
            fos = new FileOutputStream(target);
            in = fis.getChannel();//得到對應的檔案通道
            out = fos.getChannel();//得到對應的檔案通道
            in.transferTo(0, in.size(), out);//連線兩個通道,並且從in通道讀取,然後寫入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null){
                    out.close();
                }
                if (in != null){
                    in.close();
                }
                if (fos != null){
                    fos.close();
                }
                if (fis != null){
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*讀取Text檔案操作*/
    public static String readText(String filePath) {
        String lines = "";
        try {
            FileReader fileReader = new FileReader(filePath);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                lines += line + "\n";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lines;
    }

    /*寫入Text檔案操作*/
    public static void writeText(String filePath, String content,boolean isAppend) {
        FileOutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            outputStream = new FileOutputStream(filePath,isAppend);
            outputStreamWriter = new OutputStreamWriter(outputStream);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if(bufferedWriter != null){
                    bufferedWriter.close();
                }
                if (outputStreamWriter != null){
                    outputStreamWriter.close();
                }
                if (outputStream != null){
                    outputStream.close();
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 汪敏 2017-12-06
     * oss通用單張圖片上傳
     * @param picture 大文字物件陣列
     * @param filePath 檔案儲存路徑
     * @return
     */
    public static ResponseMap upload(MultipartFile picture, String filePath) {
        ResponseMap responseMap = ResponseMap.getInstance();
        List<String> imageUrlList = new ArrayList<>();
        try{
            if (picture.getSize() > 0){
                String originalFilename = picture.getOriginalFilename(); //獲取圖片原來名稱
                String filePathName = filePath + CommonUtils.uuid() + "."+ FilenameUtils.getExtension(originalFilename); //真實的圖片儲存相對路徑
                boolean isOK = AliOssUtils.saveFileObject(filePathName,picture.getInputStream());//將圖片上傳到oss伺服器
                if(isOK){
                    imageUrlList.add(filePathName);
                    responseMap.ok("上傳成功");
                }else{
                    return responseMap.error("上傳失敗");
                }
            }
            responseMap.put(ResponseMap.IMAGE_URL_LIST,imageUrlList);
        }catch(Exception e){
            e.printStackTrace();
        }
        return responseMap;
    }

    /**
     * 汪敏 2017-12-06
     * oss通用圖片批量上傳
     * @param picture 大文字物件陣列
     * @param ossFilePath 檔案儲存oss路徑,不要域名
     * @return
     */
    public static ResponseMap upload(MultipartFile[] picture, String ossFilePath) {
        ResponseMap responseMap = ResponseMap.getInstance();
        List<String> imageUrlList = new ArrayList<>();
        try{
            for (MultipartFile pic : picture) {
                if (pic.getSize() > 0){
                    String originalFilename = pic.getOriginalFilename(); //獲取圖片原來名稱
                    String filePathName = ossFilePath + CommonUtils.uuid() + "."+ FilenameUtils.getExtension(originalFilename); //真實的圖片儲存相對路徑
                    boolean isOK = AliOssUtils.saveFileObject(filePathName,pic.getInputStream());//將圖片上傳到oss伺服器
                    //boolean isOK = AliOssUtils.breakPointUpload(filePathName,pic);//將圖片上傳到oss伺服器
                    if(isOK){
                        imageUrlList.add(filePathName);
                        responseMap.put(ResponseMap.MESSAGE,"上傳成功");
                    }else{
                        return responseMap.error("上傳失敗");
                    }
                }
            }
            responseMap.put(ResponseMap.IMAGE_URL_LIST,imageUrlList);
        }catch(Exception e){
            e.printStackTrace();
        }
        return responseMap;
    }

    /**
     * 將本地檔案上傳到oss系統
     * @param localFilePath 本地檔案目錄路徑
     * @param ossFilePath oss目錄路徑
     * @return
     */
    public static ResponseMap upload(String localFilePath, String ossFilePath) {
        ResponseMap responseMap = ResponseMap.getInstance();
        try{
            File[] files = fileSort(localFilePath);
            List<String> imageUrlList = AliOssUtils.saveFileBatch(ossFilePath,files);//將圖片上傳到oss伺服器
            System.out.println("圖片上傳oss完成");
            responseMap.put(ResponseMap.IMAGE_URL_LIST,imageUrlList);
        }catch(Exception e){
            e.printStackTrace();
            responseMap.error("上傳失敗");
        }
        return responseMap;
    }



    /**
     * 汪敏 2017-12-20
     * 伺服器通用圖片批量上傳
     * @param picture 大文字物件陣列
     * @param mp4TempDir 檔案儲存全路徑
     * @return
     */
    public static boolean uploadLocal(MultipartFile[] picture, String mp4TempDir) {
        boolean bool = false;
        try{
            for (int i = 0; i < picture.length; i++) {
                if (picture[i].getSize() > 0){
                    String originalFilename = picture[i].getOriginalFilename(); //獲取圖片原來名稱
                    String filePathName = mp4TempDir + i + "."+ FilenameUtils.getExtension(originalFilename); //真實的圖片儲存相對路徑
                    picture[i].transferTo(new File(filePathName));
                }
            }
            bool = true;
            System.out.println("圖片上傳到伺服器完成");
        }catch(Exception e){
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 通過上一層目錄和目錄名得到最後的目錄層次
     * @param previousDir 上一層目錄
     * @param dirName 當前目錄名
     * @return
     */
    public static String getSaveDir(String previousDir, String dirName) {
        if (StringUtils.isNotBlank(previousDir)){
            dirName = previousDir + "/" + dirName + "/";
        }else {
            dirName = dirName + "/";
        }
        return dirName;
    }

    /**
     * 如果目錄不存在,就建立檔案
     * @param dirPath
     * @return
     */
    public static String mkdirs(String dirPath) {
        try{
            File file = new File(dirPath);
            if(!file.exists()){
                file.mkdirs();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return dirPath;
    }


    /**
     * 在Linux系統中讀取檔案時將檔案排序
     * @param filePath
     * @return
     */
    public static File[] fileSort(String filePath){
        File[] files = new File(filePath).listFiles();
        int filesLength = files.length;
        String nextFix = FilenameUtils.getExtension(files[0].getName());
        File[] fileNames = new File[filesLength];
        for (int i = 0; i < filesLength; i++) {
            for (int j = 0; j < filesLength; j++) {
                String absolutePath = files[j].getAbsolutePath();
                if (absolutePath.endsWith("/" + i + "." + nextFix) || absolutePath.endsWith("\\" + i + "." + nextFix)){
                    fileNames[i] = new File(absolutePath);
                    break;
                }
            }
        }
        return fileNames;
    }


    /**
     * 普通檔案下載,檔案在伺服器裡面
     * @param request
     * @param response
     */
    public static void download(HttpServletRequest request, HttpServletResponse response) {
        try{
            //設定檔案下載時,檔案流的格式
            String realPath = request.getServletContext().getRealPath("/");
            realPath = realPath + "index.jsp";
            System.out.println("下載地址="+realPath);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));
            BufferedOutputStream bos =  new BufferedOutputStream(response.getOutputStream());
            //下面這個變數儲存的是要下載的檔案拼接之後的完整路徑
            String downName = realPath.substring(realPath.lastIndexOf("/") + 1);
            System.out.println("下載檔名="+downName);
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(downName,"utf-8"));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            try {
                bis.close();
                bos.close();
            }catch (Exception e){
                e.printStackTrace();;
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("下載出錯");
        }
    }

    /**
     * 普通檔案下載,檔案路徑固定
     * @param targetFile 下載的檔案路徑
     * @param response
     */
    public static void download(String targetFile, HttpServletResponse response) {
        try{
            System.out.println("下載檔案路徑="+targetFile);
            //設定檔案下載時,檔案流的格式
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(targetFile));
            BufferedOutputStream bos =  new BufferedOutputStream(response.getOutputStream());
            //下面這個變數儲存的是要下載的檔案拼接之後的完整路徑
            String downName = targetFile.substring(targetFile.lastIndexOf("/") + 1);
            System.out.println("下載檔名="+downName);
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(downName,"utf-8"));
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            try {
                bis.close();
                bos.close();
            }catch (Exception e){
                e.printStackTrace();;
            }
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("下載出錯");
        }
    }

    /**
     * 下載網路檔案
     * @param targetFile
     * @param response
     */
    public static void downloadUrl(String targetFile, HttpServletResponse response) {
        try{
            URL website = new URL(targetFile);
            ReadableByteChannel rbc = Channels.newChannel(website.openStream());
            FileOutputStream fos = new FileOutputStream("D:/img/1.zip");//例如:test.txt
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("下載出錯");
        }
    }

    /**
     * 刪除檔案
     * @param fileName
     * @return
     */
    
public static boolean delete (String fileName){
    try{
        File sourceFile = new File(fileName);
        if(sourceFile.isDirectory()){
            for (File listFile : sourceFile.listFiles()) {
                delete(listFile.getAbsolutePath());
            }
        }
        return sourceFile.delete();
    }catch(Exception e){
        e.printStackTrace();
    }
    return false;
}
}

相關文章