Java 讀取、寫入文件——解決亂碼問題

    讀取文件流時,常常會遇到亂碼的現象,形成亂碼的緣由固然不多是一個,這裏主要介紹由於文件編碼格式而致使的亂碼的問題。首先,明確一點,文本文件與二進制文件的概念與差別。java

    文本文件是基於字符編碼的文件,常見的編碼有ASCII編碼,UNICODE編碼、ANSI編碼等等。二進制文件是基於值編碼的文件,你能夠根據具體應用,指定某個值是什麼意思(這樣一個過程,能夠看做是自定義編碼。)c++

    所以能夠看出文本文件基本上是定長編碼的(也有非定長的編碼如UTF-8)。而二進制文件可當作是變長編碼的,由於是值編碼嘛,多少個比特表明一個值,徹底由你決定。數組

    對於二進制文件,是千萬不能使用字符串的,由於字符串默認初始化時會使用系統默認編碼,然而,二進制文件由於自定義編碼天然與固定格式的編碼會有所衝突,因此對於二進制的文件只能採用字節流讀取、操做、寫入。
安全

    對於文本文件,由於編碼固定,因此只要在讀取文件以前,採用文件自身的編碼格式解析文件,而後獲取字節,再而後,經過指定格式初始化字符串,那麼獲得的文本是不會亂碼的。雖然,二進制文件也能夠獲取到它的文本編碼格式,可是那是不許確的,因此不能同日而語。
app

    具體操做以下:編碼

1)獲取文本文件的格式操作系統

public static String getFileEncode(String path) {
		String charset ="asci";
        byte[] first3Bytes = new byte[3];
        BufferedInputStream bis = null;
        try {
            boolean checked = false;
            bis = new BufferedInputStream(new FileInputStream(path));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "Unicode";//UTF-16LE
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
                charset = "Unicode";//UTF-16BE
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                int len = 0;
                int loc = 0;
                while ((read = bis.read()) != -1) {
                    loc++;
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) //單獨出現BF如下的,也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) 
                        //雙字節 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB編碼內
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) { //也有可能出錯,可是概率較小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
                //TextLogger.getLogger().info(loc + " " + Integer.toHexString(read));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ex) {
                }
            }
        }
        return charset;
	}

	private static String getEncode(int flag1, int flag2, int flag3) {
		String encode="";
		// txt文件的開頭會多出幾個字節,分別是FF、FE(Unicode),
		// FE、FF(Unicode big endian),EF、BB、BF(UTF-8)
		if (flag1 == 255 && flag2 == 254) {
			encode="Unicode";
		}
		else if (flag1 == 254 && flag2 == 255) {
			encode="UTF-16";
		}
		else if (flag1 == 239 && flag2 == 187 && flag3 == 191) {
			encode="UTF8";
		}
		else {
			encode="asci";// ASCII碼
		}
		return encode;
	}

2)經過文件的編碼格式讀取文件流code

/**
	 * 經過路徑獲取文件的內容,這個方法由於用到了字符串做爲載體,爲了正確讀取文件(不亂碼),只能讀取文本文件,安全方法!
	 */
	public static String readFile(String path){
		String data = null;
		// 判斷文件是否存在
		File file = new File(path);
		if(!file.exists()){
			return data;
		}
		// 獲取文件編碼格式
		String code = FileEncode.getFileEncode(path);
		InputStreamReader isr = null;
		try{
			// 根據編碼格式解析文件
			if("asci".equals(code)){
				// 這裏採用GBK編碼,而不用環境編碼格式,由於環境默認編碼不等於操做系統編碼 
				// code = System.getProperty("file.encoding");
				code = "GBK";
			}
			isr = new InputStreamReader(new FileInputStream(file),code);
			// 讀取文件內容
			int length = -1 ;
			char[] buffer = new char[1024];
			StringBuffer sb = new StringBuffer();
			while((length = isr.read(buffer, 0, 1024) ) != -1){
				sb.append(buffer,0,length);
			}
			data = new String(sb);
		}catch(Exception e){
			e.printStackTrace();
			log.info("getFile IO Exception:"+e.getMessage());
		}finally{
			try {
				if(isr != null){
					isr.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
				log.info("getFile IO Exception:"+e.getMessage());
			}
		}
		return data;
	}

3)經過文件指定的格式寫入文件ci

/**
	 * 按照指定的路徑和編碼格式保存文件內容,這個方法由於用到了字符串做爲載體,爲了正確寫入文件(不亂碼),只能寫入文本內容,安全方法
	 * 
	 * @param data
	 *          將要寫入到文件中的字節數據
	 * @param path
	 *          文件路徑,包含文件名
	 * @return boolean 
	 * 			當寫入完畢時返回true;
	 */
	public static boolean writeFile(byte data[], String path , String code){
		boolean flag = true;
		OutputStreamWriter osw = null;
		try{
			File file = new File(path);
			if(!file.exists()){
				file = new File(file.getParent());
				if(!file.exists()){
					file.mkdirs();
				}
			}
			if("asci".equals(code)){
				code = "GBK";
			}
			osw = new OutputStreamWriter(new FileOutputStream(path),code);
			osw.write(new String(data,code));
			osw.flush();
		}catch(Exception e){
			e.printStackTrace();
			log.info("toFile IO Exception:"+e.getMessage());
			flag = false;
		}finally{
			try{
				if(osw != null){
					osw.close();
				}
			}catch(IOException e){
				e.printStackTrace();
				log.info("toFile IO Exception:"+e.getMessage());
				flag = false;
			}
		}
		return flag;
	}

4)對於二進制文件並且內容不多的,例如Word文檔等,可使用以下方式讀取、寫入文件文檔

/**
	 * 從指定路徑讀取文件到字節數組中,對於一些非文本格式的內容能夠選用這個方法
	 * 			457364578634785634534
	 * @param path
	 *          文件路徑,包含文件名
	 * @return byte[]
	 * 			 文件字節數組
	 *            
	 */
	public static byte[] getFile(String path) throws IOException {
		FileInputStream stream=new FileInputStream(path);
		int size=stream.available();
		byte data[]=new byte[size];
		stream.read(data);
		stream.close();
		stream=null;
		return data;
	}



	/**
	 * 把字節內容寫入到對應的文件,對於一些非文本的文件能夠採用這個方法。
	 * @param data
	 *            將要寫入到文件中的字節數據
	 * @param path
	 *            文件路徑,包含文件名
	 * @return boolean isOK 當寫入完畢時返回true;
	 * @throws Exception
	 */
	public static boolean toFile(byte data[], String path) throws Exception {
		FileOutputStream out=new FileOutputStream(path);
		out.write(data);
		out.flush();
		out.close();
		out=null;
		return true;
	}
相關文章
相關標籤/搜索