1. 程式人生 > >把 編碼為UTF-8的XML檔案轉為字元流輸出

把 編碼為UTF-8的XML檔案轉為字元流輸出

package com.wxd.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;

public class te {
	
	// 把xml檔案讀成 字元流  
	public static String xmlToLiu(String path) throws Exception {  
	    File file = new File(path);  
	    if (!file.exists() || file.isDirectory()) {  
	        throw new FileNotFoundException();  
	    }  
	    // 以"GB2312"編碼,解決中文亂碼問題  
	    InputStreamReader read = new InputStreamReader(  
	            new FileInputStream(file), "utf-8");  
	    BufferedReader br = new BufferedReader(read);  
	    String temp = null;  
	    StringBuffer sb = new StringBuffer();  
	    temp = br.readLine();  
	    while (temp != null) {  
	        sb.append(temp + "\n");  
	        temp = br.readLine();  
	    }  
	    br.close();  
	    read.close();  
	    return sb.toString();  
	}  
	
	public static void main(String[] args) throws Exception {
		String path = "E:\\1.xml";
		System.out.println(xmlToLiu(path));
	}
}
1.xml 中檔案內容為:
<?xml version="1.0" encoding="GB2312" standalone="yes" ?>  
<TX>  
  <REQUEST_SN>請求序列碼</REQUEST_SN>  
  <CUST_ID>客戶號</CUST_ID>  
  <USER_ID>操作員號</USER_ID>  
  <PASSWORD>密碼</PASSWORD>  
  <TX_CODE>6W0100</TX_CODE>  
  <LANGUAGE>CN</LANGUAGE>  
  <TX_INFO>  
    <ACC_NO>賬號</ACC_NO>  
  </TX_INFO>  
</TX> 
控制檯輸出:

注意:使用 InputStreamReader read = new InputStreamReader(   new FileInputStream(file), "utf-8");   時,後面的

charsetName 也就是UTF-8的位置要和xml檔案的編碼一致。