文件生成或複製的工具類

直接上代碼,可以直接用的
package com.bc.ywjphone.readily.utils;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2016/12/30 0030.
 */
public class FileUtil {

    /**
     * 創建目錄
     *
     * @param dir 目錄
     */
    public static void mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
        } catch (Exception e) {
            Log.e("TAG","創建目錄操作出錯: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 新建文件
     *
     * @param fileName String 包含路徑的文件名 如:E:\phsftp\src\123.txt
     * @param content  String 文件內容
     */
    public static void createNewFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            Log.e("TAG","新建文件操作出錯: " + e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * 刪除文件
     *
     * @param fileName 包含路徑的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            java.io.File delFile = new java.io.File(filePath);
            delFile.delete();
        } catch (Exception e) {
            Log.e("TAG","刪除文件操作出錯: " + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 刪除文件夾
     *
     * @param folderPath 文件夾路徑
     */
    public static void delFolder(String folderPath) {
        try {
            // 刪除文件夾裏面所有內容
            delAllFile(folderPath);
            String filePath = folderPath;
            java.io.File myFilePath = new java.io.File(filePath);
            // 刪除空文件夾
            myFilePath.delete();
        } catch (Exception e) {
            Log.e("TAG","刪除文件夾操作出錯" + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 刪除文件夾裏面的所有文件
     *
     * @param path 文件夾路徑
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] childFiles = file.list();
        File temp = null;
        for (int i = 0; i < childFiles.length; i++) {
            //File.separator與系統有關的默認名稱分隔符
            //在UNIX系統上,此字段的值爲'/';在Microsoft Windows系統上,它爲 '\'。
            if (path.endsWith(File.separator)) {
                temp = new File(path + childFiles[i]);
            } else {
                temp = new File(path + File.separator + childFiles[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + childFiles[i]);// 先刪除文件夾裏面的文件
                delFolder(path + "/" + childFiles[i]);// 再刪除空文件夾
            }
        }
    }


    /**
     * 複製單個文件
     *
     * @param srcFile 包含路徑的源文件 如:E:/phsftp/src/abc.txt
     * @param dirDest 目標文件目錄;若文件目錄不存在則自動創建  如:E:/phsftp/dest
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            mkdir(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest + "/" + new File(srcFile).getName());
            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            Log.e("TAG","複製文件操作出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 複製文件夾
     *
     * @param oldPath String 源文件夾路徑 如:E:/phsftp/src
     * @param newPath String 目標文件夾路徑 如:E:/phsftp/dest
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夾不存在 則新建文件夾
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + File.separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夾
                    copyFolder(oldPath + "/" + files[i], newPath + "/" + files[i]);
                }
            }
        } catch (Exception e) {
            Log.e("TAG","複製文件夾操作出錯:" + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 移動文件到指定目錄
     *
     * @param oldPath 包含路徑的文件名 如:E:/phsftp/src/ljq.txt
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    /**
     * 移動文件到指定目錄,不會刪除文件夾
     *
     * @param oldPath 源文件目錄  如:E:/phsftp/src
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFile(oldPath);
    }

    /**
     * 移動文件到指定目錄,會刪除文件夾
     *
     * @param oldPath 源文件目錄  如:E:/phsftp/src
     * @param newPath 目標文件目錄 如:E:/phsftp/dest
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

    /**
     * 解壓zip文件
     *
     * @param srcDir  解壓前存放的目錄
     * @param destDir 解壓後存放的目錄
     * @throws Exception
     */
//    public static void jieYaZip(String srcDir, String destDir) throws Exception {
//        int leng = 0;
//        byte[] b = new byte[1024 * 2];
//        /** 獲取zip格式的文件 **/
//        File[] zipFiles = new FileFilterByExtension("zip").getFiles(srcDir);
//        if (zipFiles != null && !"".equals(zipFiles)) {
//            for (int i = 0; i < zipFiles.length; i++) {
//                File file = zipFiles[i];
//                /** 解壓的輸入流 * */
//                ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
//                ZipEntry entry = null;
//                while ((entry = zis.getNextEntry()) != null) {
//                    File destFile = null;
//                    if (destDir.endsWith(File.separator)) {
//                        destFile = new File(destDir + entry.getName());
//                    } else {
//                        destFile = new File(destDir + "/" + entry.getName());
//                    }
//                    /** 把解壓包中的文件拷貝到目標目錄 * */
//                    FileOutputStream fos = new FileOutputStream(destFile);
//                    while ((leng = zis.read(b)) != -1) {
//                        fos.write(b, 0, leng);
//                    }
//                    fos.close();
//                }
//                zis.close();
//            }
//        }
//    }

    /**
     * 壓縮文件
     *
     * @param srcDir  壓縮前存放的目錄
     * @param destDir 壓縮後存放的目錄
     * @throws Exception
     */
    public static void yaSuoZip(String srcDir, String destDir) throws Exception {
        String tempFileName = null;
        byte[] buf = new byte[1024 * 2];
        int len;
        //獲取要壓縮的文件
        File[] files = new File(srcDir).listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    if (destDir.endsWith(File.separator)) {
                        tempFileName = destDir + file.getName() + ".zip";
                    } else {
                        tempFileName = destDir + "/" + file.getName() + ".zip";
                    }
                    FileOutputStream fos = new FileOutputStream(tempFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    ZipOutputStream zos = new ZipOutputStream(bos);// 壓縮包

                    ZipEntry ze = new ZipEntry(file.getName());// 壓縮包文件名
                    zos.putNextEntry(ze);// 寫入新的ZIP文件條目並將流定位到條目數據的開始處

                    while ((len = bis.read(buf)) != -1) {
                        zos.write(buf, 0, len);
                        zos.flush();
                    }
                    bis.close();
                    zos.close();

                }
            }
        }
    }


    /**
     * 讀取數據
     *
     * @param inSream
     * @param charsetName
     * @return
     * @throws Exception
     */
    public static String readData(InputStream inSream, String charsetName) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inSream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }

    /**
     * 一行一行讀取文件,適合字符讀取,若讀取中文字符時會出現亂碼
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static Set<String> readFile(String path) throws Exception {
        Set<String> datas = new HashSet<String>();
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        String line = null;
        while ((line = br.readLine()) != null) {
            datas.add(line);
        }
        br.close();
        fr.close();
        return datas;
    }
}

發佈了32 篇原創文章 · 獲贊 97 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章