JAVA操作檔案

來源:互聯網
上載者:User

標籤:java 操作檔案系統

/*

 */
package com.***.app.mappcore.impl.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

import com.ygsoft.ecp.service.log.EcpLogFactory;
import com.ygsoft.ecp.service.log.IEcpLog;
import com.ygsoft.ecp.service.tool.StringUtil;

/**
 * 檔案處理.<br>
 *
 * @author mapengfei <br>
 * @version 1.0.0 2016年4月14日<br>
 * @see
 * @since JDK 1.5.0
 */
public class ForderUtil {
    /**
     * 日誌
     */
    private static final IEcpLog LOG = EcpLogFactory.getLog(ForderUtil.class);

    /**
     * 服務的基準路徑.
     */
    private static String BASE_PATH = SystemConfigUtil.get("SERVER_BASE_HOME", "FTP") + "\\ecpCloudServer\\wlp";
    /**
     * 服務節點的路徑.
     */
    private static String SERVER_PATH = BASE_PATH + "\\usr\\servers";

    /**
     * 根據路徑刪除指定的目錄或檔案,無論存在與否
     *
     * @param sPath
     *            要刪除的目錄或檔案
     * @return 刪除成功返回 true,否則返回 false。
     */
    public static boolean deleteFolder(final String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 判斷目錄或檔案是否存在
        if (!file.exists()) { // 不存在返回 false
            return flag;
        } else {
            // 判斷是否為檔案
            if (file.isFile()) { // 為檔案時調用刪除檔案方法
                return deleteFile(sPath);
            } else { // 為目錄時調用刪除目錄方法
                return deleteDirectory(sPath);
            }
        }
    }

    /**
     * 刪除目錄(檔案夾)以及目錄下的檔案
     *
     * @param sPath
     *            被刪除目錄的檔案路徑
     * @return 目錄刪除成功返回true,否則返回false
     */
    private static boolean deleteDirectory(String sPath) {
        // 如果sPath不以檔案分隔字元結尾,自動添加檔案分隔字元
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        // 如果dir對應的檔案不存在,或者不是一個目錄,則退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        // 刪除檔案夾下的所有檔案(包括子目錄)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 刪除子檔案
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 刪除子目錄
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 刪除目前的目錄
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 刪除單個檔案
     *
     * @param sPath
     *            被刪除檔案的檔案名稱
     * @return 單個檔案刪除成功返回true,否則返回false
     */
    private static boolean deleteFile(final String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路徑為檔案且不為空白則進行刪除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 檔案通道複製方案
     *
     * @param s
     * @param t
     */
    public static void fileChannelCopy(final File from, final File to) {
        // 檔案輸入資料流
        FileInputStream fi = null;
        // 檔案輸出資料流
        FileOutputStream fo = null;
        // 輸入通道
        FileChannel in = null;
        // 輸出通道
        FileChannel out = null;
        try {
            // 讀取流
            fi = new FileInputStream(from);
            // 輸出資料流
            fo = new FileOutputStream(to);
            // 取得檔案流通道
            in = fi.getChannel();
            out = fo.getChannel();
            // 通道串連
            in.transferTo(0, in.size(), out);
        } catch (FileNotFoundException e) {
            // 建立讀出流異常
            e.printStackTrace();
        } catch (IOException e) {
            // 通道聯通出現異常
            e.printStackTrace();
        } finally {
            try {
                fi.close();
                in.close();
                fo.close();
                out.close();
            } catch (IOException e) {
                // 流關閉異常
                e.printStackTrace();
            }

        }
    }

    /**
     * 從fromPath複製檔案及目錄到toPath
     *
     * @param fromPath
     *            母體檔案路徑
     * @param toPath
     *            目標檔案路徑
     * @param isZip
     *            壓縮標示
     * @param zipPath
     *            zip壓縮後的路徑(該參數與isZip聯合使用)
     */
    public static void copyFile(String fromPath, String toPath, final String zipPath, final boolean isZip) {
        // 如果sPath不以檔案分隔字元結尾,自動添加檔案分隔字元
        if (!fromPath.endsWith(File.separator)) {
            fromPath = fromPath + File.separator;
        }
        File dirFile = new File(fromPath);
        mkdirsFileByPath(toPath);
        if (dirFile.isDirectory()) {
            // 複製檔案夾下的所有檔案(包括子目錄)
            File[] files = dirFile.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                // 如果是檔案
                if (f.isFile()) {
                    File toFile = new File(toPath + "\\" + f.getName());
                    fileChannelCopy(f, toFile);
                } else {
                    toPath = toPath + "\\" + f.getName();
                    mkdirsFileByPath(toPath);
                }
            }
        } else {
            File toFile = new File(toPath + "\\" + dirFile.getName());
            fileChannelCopy(dirFile, toFile);

        }
        if (isZip && StringUtil.isNotEmptyString(zipPath)) {
            try {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("開始壓縮記錄檔,壓縮後的檔案路徑為" + fromPath + "\\" + "log.zip");
                }
                File zipFile = new File(zipPath);
                if (zipFile.exists()) {
                    ForderUtil.deleteFolder(zipPath);
                }
                ZipMultiFile.zip(zipPath, "", toPath);
                ForderUtil.deleteFolder(toPath);
            } catch (Exception e) {
                if (LOG.isDebugEnabled()) {
                    LOG.info("ForderUtil.copyFile壓縮檔過程中失敗");
                }
                e.printStackTrace();
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.info("ForderUtil.copyFile方法壓縮標示為false或壓縮路徑為null" + zipPath);
            }
        }
    }

    /**
     * 取得LOG日誌壓縮檔
     *
     * @param zipPath
     * @param mappName
     * @return
     */
    public static String getLogZip(final String mappName) {
        String toPath = SERVER_PATH + "\\" + mappName + "\\log";
        String fromPath = SERVER_PATH + "\\" + mappName + "\\logs\\console.log";
        String zipPath = SERVER_PATH + "\\" + mappName + "\\log.zip";
        copyFile(fromPath, toPath, zipPath, true);
        return zipPath;
    }

    /**
     * 自動建立path
     *
     * @param path
     * @return
     */
    private static void mkdirsFileByPath(final String path) {
        File toFile = new File(path);
        if (!toFile.exists()) {
            toFile.mkdirs();
        }
    }

    public static void main(final String[] args) throws Exception {
        String from = "D:\\ygecpcloud\\ecpCloudServer\\wlp\\usr\\servers\\mappstore\\logs";
        String to = "D:\\ygecpcloud\\ecpCloudServer\\wlp\\usr\\servers\\mappstore\\log";
        copyFile(from, to, "D:\\ygecpcloud\\ecpCloudServer\\wlp\\usr\\servers\\mappstore\\l.zip", true);
    }

}

JAVA操作檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.