文件操作工具類 1.刪除目錄下的所有文件及子目錄下所有文件 2.保存文件 3.獲取文件流後自動刪除文件 4.複製文件 5.應用根目錄

文件操作工具類

1.刪除目錄下的所有文件及子目錄下所有文件

2.保存文件

3.獲取文件流後自動刪除文件

4.複製文件 

5.獲取應用根目錄 

pom依賴:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.8.1</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.6</version>
</dependency>

代碼:

package com.binmma.utils;/**
 * Created by binmma on 2019/2/27 0027.
 */

import org.apache.commons.io.input.AutoCloseInputStream;
import org.apache.commons.io.input.ClosedInputStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;

/**
 * @Author binmma
 * @Date 2019/2/27 0027 下午 5:33
 * @Desc 文件操作工具類
 **/
public class FileUtils {
    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    /**讀取文件時每行讀入的最大字節數*/
    private static final int DEFAULT_LINE_SIZE = 4096;

    /**應用根目錄*/
    private static String webRoot;

    /**
     * 刪除目錄下的所有文件及子目錄下所有文件
     * @param path 文件目錄
     * @return
     */
    public static boolean deleteDir(String path){
       return  deleteDir(new File(path));
    }

    /**
     * 刪除文件
     * @param path 文件
     * @return 返回刪除結果
     */
    public static boolean deleteFile(String path) {
        try {
            if (StringUtils.isBlank(path)) {
                return false;
            }
            File file = new File(path);
            if (file.isFile()) {
                return file.delete();
            }
        } catch (Exception e) {
            logger.error("文件刪除異常!異常文件爲:{}",path, e);
        }
        return false;
    }

    /**
     * 刪除文件
     * @param file 文件
     * @return 返回刪除結果
     */
    public static boolean deleteFile(File file) {
        try {
            if (file.isFile()) {
                return file.delete();
            }
        } catch (Exception e) {
            String fileName = null;
            if (file != null) {
                fileName = file.getAbsolutePath();
            }
            logger.error("文件刪除異常!異常文件爲:{}", fileName, e);
        }
        return false;
    }

    /**
     * 獲取java IO臨時目錄文件
     * @return
     */
    public static String getTempPath() {
        return String.format("%s\\", SystemUtils.getJavaIoTmpDir().getPath());
    }
    /**
     * 刪除目錄下的所有文件及子目錄下所有文件
     * @param dir 將要刪除的文件目錄
     * @return boolean
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //遞歸刪除目錄中的子目錄下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目錄此時爲空,可以刪除
        return dir.delete();
    }
    /**
     * 保存文件
     *
     * @param inputFile
     * @param filePath 文件保存路徑
     * @param fileName 文件名稱
     */
    public static boolean saveFileData(InputStream inputFile, String filePath,
                                    String fileName){
        File path = new File(filePath);
        if (!path.exists()) {
            path.mkdirs();
        }
        File file = new File(path, fileName);
        FileOutputStream outFile = null;
        byte[] abyteFile = new byte[DEFAULT_LINE_SIZE];
        try {
            outFile = new FileOutputStream(file);
            int iLen;
            while ((iLen = inputFile.read(abyteFile)) != -1)
                outFile.write(abyteFile, 0, iLen);
        } catch (IOException e) {
            logger.error("文件【{}】保存失敗",fileName,e);
            return false;
        } finally {
            try{
                outFile.close();
                inputFile.close();
            }catch (Exception e){
                logger.error("文件流關閉失敗",e);
            }
        }
        return true;
    }

    /**
     * 獲取文件流後自動刪除文件
     * @param tmpPath
     * @return
     */
    public static InputStream getStream(String tmpPath){
        File file = new File(tmpPath);
        InputStream fs = null;
        try {
            fs = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error("文件【{}】不存在",tmpPath,e);
        }
        return new FileUtils.TempInputStream(file.getAbsolutePath(), fs);
    }
    private static class TempInputStream extends AutoCloseInputStream {
        private String filePath;
        public TempInputStream(String filePath, InputStream inputStream) {
            super(inputStream);
            this.filePath = filePath;
        }
        public void close() throws IOException {
            this.in.close();
            this.in = new ClosedInputStream();
            FileUtils.deleteFile(filePath);
        }
    }
    /**
     * 複製文件數據
     * @param srcFile 源文件
     * @param desFile 目標文件
     * @return
     */
    private static boolean copyFile(String srcFile, String desFile){
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            inBuff = new BufferedInputStream(new FileInputStream(srcFile));
            outBuff = new BufferedOutputStream(new FileOutputStream(desFile));
            // 緩衝數組
            byte[] b = new byte[DEFAULT_LINE_SIZE];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            outBuff.flush();
        } catch (IOException e) {
            logger.error("文件操作失敗");
            return false;
        } finally {
            try {
                inBuff.close();
                outBuff.close();
            } catch (IOException e) {
                logger.error("文件流關閉失敗");
            }
        }
        return true;
    }

    /**
     * 應用根目錄
     * @return 應用根目錄
     */
    public static String getWebRoot() {
        if (webRoot == null) {
            URL url = FileUtils.class.getClassLoader().getResource("");
            String path = url.getPath();
            String separator = "/";
            char s = File.separatorChar;
            /**
             * 處理windows平臺環境,對於路徑linux和windows環境需要進行特殊處理。
             */
            if ('\\' == s) {
                if (path.startsWith(separator)) {
                    path = path.substring(1);
                }
            }
            path = path.substring(0, path.length() - 1);
            int index = path.lastIndexOf(separator);
            path = path.substring(0, index);
            index = path.lastIndexOf(separator);
            path = path.substring(0, index + 1);
            webRoot = path;
        }
        return webRoot;
    }
    /**
     * 獲取路徑
     * @param root 目錄根目錄
     * @return 需要目錄的路徑
     */
    public static String getPath(String root) {
        String separator = "/";
        String tempFolder = getWebRoot() + root + separator;
        File file = new File(tempFolder);
        if (!file.isDirectory()) {
            boolean creat = file.mkdirs();
            if (!creat) {
                logger.info("創建臨時路徑{}失敗", file.getAbsolutePath());
            }
        }
        return tempFolder;
    }

    public static void main(String[] args) throws IOException {
        String webRoot = getWebRoot();
        String path1 = getPath("temp");
        logger.error(path1);
        String path = "d:\\log - 副本";
//        boolean b = deleteDir(new File(path));
//        boolean b = deleteDir(path);
//        boolean b = deleteFile("D:\\log\\log\\新建文本文檔.txt");
//        logger.error("刪除是否成功{}",b);
//        InputStream in = getStream("D:\\LL2.zip");

//        InputStream in = new FileInputStream("D:\\LL.zip");

//        boolean b = saveFileData(in, "D:\\inputStrean\\input2", "LL9.zip");
//        logger.error(b+"");
//        FileOutputStream fos = new FileOutputStream("D:\\LL6.zip");
//        byte[] b = new byte[1024];
//        int length;
//        while((length= in.read(b))>0){
//            fos.write(b,0,length);
//        }
//        in.close();
//        fos.close();

    }
}

原文:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章