Java針對文件操作代碼分享

package com.idbp.common.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.StringUtils;

import com.dap.config.ParamsContainer;
import com.dap.exception.BusinessException;

public class FileUtil {

private final static String CHAR_SET = "UTF-8";
private final static int NEW_LINE_CHAR_BYTE = System.getProperty("line.separator").getBytes().length;
private final static String TEMPATH = ParamsContainer.getString("icon.fileTranPath");


/**
 * 
 * @param fileName
 *            文件路徑+文件名
 * @param content
 *            文件內容
 * @throws Exception
 */
public static void write(String fileName, String content) throws Exception {
    write(fileName, content, false);
}


/**
 * 追寫文件
 * 
 * @param fileName
 * @param content
 * @param append
 * @throws Exception
 */
public static void write(String fileName, String content, boolean append) throws Exception {
    File file = new File(fileName);
    File fileParent = file.getParentFile();
    if (!fileParent.exists()) {
        boolean exist = fileParent.mkdirs();
        if (!exist) {
            throw new Exception("生成文件路徑" + fileParent.getAbsolutePath() + "失敗!");
        }
    }
    BufferedWriter bw =
            new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), CHAR_SET));
    try {
        bw.write(content);
    } finally {
        bw.close();
    }

}


/**
 * 讀取文件將每行放到List裏 , 只允許讀取小文件時使用此方法
 * 
 * @param fileName
 * @return
 * @throws Exception
 */
public static List<String> readFileToList(String fileName) throws Exception {
    List<String> list = new ArrayList<String>();
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
    String buf = null;
    try {
        while ((buf = br.readLine()) != null) {
            list.add(buf);
        }
    } finally {
        br.close();
    }
    return list;
}


/**
 * 獲取文件的總行數,文件需要每一行均含有固定長度
 * 
 * @param fileName
 * @param lineByteSize
 *            單行的固定字節數 ,小於1表示無固定長度
 * @return
 * @throws Exception
 */
public static long getFileRowCount(String fileName, long lineByteSize) throws Exception {
    long rowCount = 0;
    if (lineByteSize > 0) {
        long len = new File(fileName).length();
        rowCount = (len + NEW_LINE_CHAR_BYTE) / (lineByteSize + NEW_LINE_CHAR_BYTE);// 加上換行符字節數
    } else {
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
        try {
            while (br.readLine() != null) {
                rowCount++;
            }
        } finally {
            br.close();
        }
    }
    return rowCount;
}


/**
 * 讀取每行無固定長度的文件,將每行放到一個List返回,List最後一個元素爲已讀取的內容字節數值(skipByte+這次讀取的字節數)
 * 
 * @param fileName
 *            文件名
 * @param skipByte
 *            跳過的字節數
 * @param maxLine
 *            最大行數
 * @return
 * @throws Exception
 */
public static List<String> readFileToList(String fileName, long skipByte, long maxLine) throws Exception {
    List<String> list = new ArrayList<String>();
    BufferedReader br =
            new BufferedReader(new InputStreamReader(new FileInputStream(fileName), CHAR_SET));
    String buf = null;
    long lineNum = 0;
    long byteSize = skipByte;
    try {
        br.skip(skipByte);
        while ((buf = br.readLine()) != null && ++lineNum <= maxLine) {
            list.add(buf);
            byteSize += buf.getBytes().length;
            byteSize += NEW_LINE_CHAR_BYTE;// 換行符佔兩個字節
        }
    } finally {
        br.close();
    }
    list.add(String.valueOf(byteSize));
    return list;
}


/**
 * 讀取固定行長度的文件,每行記錄存放到List中返回
 * 
 * @param fileName
 *            文件名
 * @param startLineIndex
 *            起始行,從0開始
 * @param lineByteSize
 *            每行固定的字節數
 * @param maxLine
 *            讀取的最大行數
 * @return
 * @throws Exception
 */
public static List<String> readFileToList(String fileName, long startLineIndex, long lineByteSize,
        long maxLine) throws Exception {
    List<String> list = new ArrayList<String>();
    BufferedReader br =
            new BufferedReader(new InputStreamReader(new FileInputStream(fileName), CHAR_SET));
    String buf = null;
    long lineNum = 0;
    try {
        br.skip(startLineIndex * (lineByteSize + NEW_LINE_CHAR_BYTE));
        while ((buf = br.readLine()) != null && ++lineNum <= maxLine) {
            list.add(buf);
        }
    } finally {
        br.close();
    }
    return list;
}


/**
 * 新建目錄
 * 
 * @param folderPath
 *            String 如 c:/fqf
 * @return boolean
 */
public static void newFolder(String folderPath) {
    String filePath = folderPath;
    filePath = filePath.toString();
    java.io.File myFilePath = new java.io.File(filePath);
    if (!myFilePath.exists()) {
        myFilePath.mkdirs();
    }
}


/***
 * 解析txt文件
 * 
 * @param filePath
 *            String eg:"d:/1.txt"
 * @return String[]
 */
public static String[] readFile(String filePath) {
    File file = new File(filePath);
    String line = null;
    List list = new ArrayList();
    String[] array = null;

    try {
        if (file.isFile() && file.exists()) {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                String a = (String) list.get(i);
                array[i] = a;
            }
            br.close();
        } else {
            throw new BusinessException("BBPF0016");// 找不到解析文件
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return array;
}


/***
 * 解析txt文件格式爲GBK
 * 
 * @param filePath
 *            String eg:"d:/1.txt"
 * @return String[]
 */
public static String[] readFileForGBK(String filePath) {
    File file = new File(filePath);
    String line = null;
    List list = new ArrayList();
    String[] array = null;

    try {
        if (file.isFile() && file.exists()) {
            BufferedReader br =
                    new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            array = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                String a = (String) list.get(i);
                array[i] = a;
            }
            br.close();
        } else {
            throw new BusinessException("BBPF0016");// 找不到解析文件
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return array;
}


/**
 * 判斷文件是否存在
 * 
 * @param path
 * @return
 */
public static boolean isExists(String path) {
    boolean flag = false;
    if (!StringUtils.isEmpty(path)) {
        File f = new File(path);
        flag = f.exists();
    }
    return flag;
}


/**
 * 新建目錄.
 * 
 * @param path
 *            文件路徑
 * @throws Exception
 */
public static void createDirectory(String path) {
    if (StringUtils.isEmpty(path)) {
        return;
    }
    try {
        // 獲得文件對象
        File f = new File(path);
        if (!f.exists()) {
            // 如果路徑不存在,則創建
            f.mkdirs();
        }
    } catch (Exception e) {
        throw new BusinessException("BBPF0016");// 找不到解析文件
    }
}


/**
 * 獲取文件後綴名
 * 
 * @param str
 * @return
 */
public static String getSuffix(String str) {
    String suffix = "";
    if (str != null && !("").equals(str)) {
        if (str.lastIndexOf(".") != -1) {
            suffix = str.substring(str.lastIndexOf(".") + 1);
        }
    }
    return suffix;
}


/**
 * 文件刪除
 * 
 * @param filePath
 * @return
 */
public static boolean deleteFile(String filePath) {// 刪除單個文件
    boolean flag = false;
    File file = new File(filePath);
    if (file.isFile() && file.exists()) {// 路徑爲文件且不爲空則進行刪除
        file.delete();// 文件刪除
        flag = true;
    }
    return flag;
}


/**
 * URL文件下載
 * 
 * @param urlString
 *            下載URL路徑
 * @param filename
 *            文件名
 */
public static String download(String urlString, String filename) {
    String filePath = null;
    URL url = null;
    InputStream is = null;
    OutputStream os = null;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new BusinessException("BBPF0025", "下載文件");
    }

    try {
        URLConnection con = url.openConnection();
        FileUtil.createDirectory(TEMPATH); // 創建目錄文件夾
        is = con.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        os = new FileOutputStream(TEMPATH + filename);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        filePath = TEMPATH + filename;
    } catch (IOException e) {
        throw new BusinessException("BBPF0025", "下載文件");
    } finally {
        try {
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return filePath;
}


/**
 * 文件解壓
 * 
 * @param sourcedir
 *            解壓文件路徑
 */
public static void unGzipFile(String sourcedir) {
    String ouputfile = "";
    try {
        FileInputStream fin = new FileInputStream(sourcedir); // 建立文件輸入流
        GZIPInputStream gzin = new GZIPInputStream(fin); // 建立gzip解壓工作流
        ouputfile = sourcedir.substring(0, sourcedir.lastIndexOf('.'));
        FileOutputStream fout = new FileOutputStream(ouputfile);

        int num;
        byte[] buf = new byte[1024];

        while ((num = gzin.read(buf, 0, buf.length)) != -1) {
            fout.write(buf, 0, num);
        }

        gzin.close();
        fout.close();
        fin.close();
    } catch (Exception ex) {
        System.err.println(ex.toString());
    }
    return;
}


/**
 * 文件追加寫入
 * 
 * @param fileContent
 * @throws Exception
 * @throws IOException
 */
public static void writeFile(String fileContent, String file, int i) throws Exception {

    FileOutputStream writerStream = null;
    BufferedWriter writer = null;
    try {
        writerStream = new FileOutputStream(file, true);
        writer = new BufferedWriter(new OutputStreamWriter(writerStream, CHAR_SET));

        if (i == 0) {
            writer.write(fileContent + "\n");
        } else {
            writer.write(fileContent);
        }
    } finally {
        try {
            writer.close();
            writerStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

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