java 讀 寫 文本文件工具類(按行讀取)

package com.test.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 寫文件工具
 * @author guishuanglin
 *
 */
public class WriteFileUtils {
	private static Log logger = LogFactory.getLog(WriteFileUtils.class);
	
	private static String fileSplit = "/";

	/**
	 * 寫文件
	 * @param in 讀取流
	 * @param out 寫入流
	 * @return 
	 * @throws Exception
	 */
	public static boolean writeFile(InputStream in, OutputStream out) {
		boolean b = false;
		try {
			int bathSize = 200;
			int i =0;
			long outSize = 0L;
			byte[] bytes = new byte[10240];//10k,根據硬盤緩存大小調節
			int c;
			while ((c = in.read(bytes)) != -1) {
				out.write(bytes, 0, c);
				outSize += c;
				i++;
				if((i>0 && (i% bathSize)== 0) || c <=0) {
					logger.info("正在寫文件本次寫入: "+ c +" btyes, 總計已寫:"+outSize);
				}
			}
			in.close();
			out.close();
		} catch (Exception e) {
			logger.error("寫入文件時失敗,可能磁盤已滿,或者其它原因.", e);
		}
		
		return b;
	}
	
	/**
	 * 寫文件
	 * @param srcName 源文件名稱,不包含路徑
	 * @param destName 目標文件名稱,不包含路徑
	 * @param srcDir 源目錄
	 * @param destDir 目標目錄
	 * @param srcEncode 源字符集
	 * @param destEncode 目標字符集
	 * @return
	 */
	public static boolean writeFile(String srcName, String destName, String srcDir, String destDir, String srcEncode, String destEncode) {
		boolean b = false;
		List<String> srcList = readFileData(srcName, srcDir, srcEncode);
		if(srcList == null || srcList.size() ==0) {
			return b;
		}
		b = writeFile(srcList, destName, destDir, destEncode);
		return b;
	}
	
	public static boolean writeFile(List<String> srcList, String destName, String destDir, String destEncode) {
		boolean b = false;
		FileOutputStream out = null;
		try {
			if(srcList==null || srcList.size()==0) {
				return true;
			}
			String outPathFileName = destDir + fileSplit +destName;
			out = getFileOutStream(destName, destDir);
			if(out ==null) {
				return false;
			}
			StringBuffer bf = new StringBuffer(128);
			int bathSize = 200;
			long outSize = 0L;
			byte[] bytes = new byte[20480];//20k,根據硬盤緩存大小調節
			byte[] inbytes = null;
			for(int i=0; i<srcList.size(); i++){
				bf.append(srcList.get(i));
				if((i>0 && (i% bathSize)== 0) || (i+1) ==srcList.size()){
					//不管原來什麼編碼, 把字符按目標編碼換
					inbytes = bf.toString().getBytes(destEncode);
					ByteArrayInputStream in = new ByteArrayInputStream(inbytes);
					int c;
					while ((c = in.read(bytes)) != -1) {
						out.write(bytes, 0, c);
						outSize += c;
					}
					in.close();
					in = null;
					bf = new StringBuffer(128);
					logger.info("正在寫文件["+outPathFileName+"],本次寫入: "+inbytes.length+" btyes, 總計已寫:"+outSize);
				}
			}
			bytes =null;
			inbytes =null;
			return true;
		} catch (Exception e) {
			b = false;
			logger.error("寫入文件時失敗,可能磁盤已滿,或者其它原因.", e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				out = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return b;
	}
	
	/**
	 * 讀取參數文件文體內容
	 * @param destName 目標文件名稱,不包含路徑
	 * @param destDir 目標目錄
	 * @param destEncode 目標字符集
	 */
	public static List<String> readFileData(String destName, String destDir, String destEncode) {
		List<String> result = null;
		FileInputStream inStream = null;
		BufferedReader bufReader = null;
		String inPathFileName = destDir + fileSplit +destName;
		try {
			inStream = getFileInStream(destName, destDir);
			if(inStream ==null) {
				return null;
			}
			bufReader = new BufferedReader(new InputStreamReader(inStream, destEncode));
			String read = null;
			result = new ArrayList<String>();
			while ((read = bufReader.readLine()) != null) {
				result.add(read);
			}
		} catch (Exception e) {
			result = null;
			logger.error("讀取文件失敗,"+inPathFileName, e);
		} finally {
			try {
				if (bufReader != null) {
					bufReader.close();
				}
				bufReader = null;
				if (inStream != null) {
					inStream.close();
				}
				inStream = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		logger.info("讀取文件行數: "+ (result ==null? 0 :result.size()) +", "+inPathFileName);
		return result;
	}
	
	/**
	 * 沒有目錄則創建
	 */
	public static boolean mkDirs(String srcDir) {
		boolean b = false;
		File dir = new File(srcDir);
		if (! dir.exists()) {
			b = dir.mkdirs();
		}else {
			b = true;
		}
		return b;
	}
	
	/**
	 * 刪除文件
	 */
	public static boolean deleteFile(String srcName, String srcDir) {
		boolean b = false;
		String dirFileName = srcDir + fileSplit +srcName;
		File outf = new File(dirFileName);
		if (outf.exists()) {
			b = outf.delete();
		}else {
			b = true;
		}
		return b;
	}
	
	/** 獲取輸出文件流 */
	public static FileOutputStream getFileOutStream(String srcName, String srcDir) {
		FileOutputStream out = null;
		try {
			String pathFileName = srcDir + fileSplit +srcName;
			if(! mkDirs(srcDir)) {
				return null;
			}
			out = new FileOutputStream(pathFileName);
		} catch (Exception e){
			out = null;
		}
		//FileUtils.moveFile(srcFile, destFile);
		return out;
	}
	
	/** 獲取讀取文件流 */
	public static FileInputStream getFileInStream(String srcName, String srcDir) {
		FileInputStream in = null;
		try {
			String pathFileName = srcDir + fileSplit +srcName;
			File inf = new File(pathFileName);
			if ((inf == null) || (! inf.exists() )) {
				return null;
			}
			in = new FileInputStream(pathFileName);
		} catch (Exception e){
			in = null;
		}
		return in;
	}
	
}

這個沒有什麼說的, 工具類, 很常用.

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