字符集之間轉換讀取和寫入
阿新 • • 發佈:2018-03-27
Output Stream Writer import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class Main_GBK_Trans_UTF8 {
public static void main(String[] args) {
writeFileUseGBK();
readFileUseGBK();
}
public static void writeFileUseGBK() {
OutputStreamWriter ow=null;
try {
// 創建字節流
// OutputStreamWriter 是字符流通向字節流的橋梁
ow=new OutputStreamWriter(new FileOutputStream("E:/gbk.txt"), "GBK");
// 使用GBK編碼寫入,同時也只能使用GBK格式讀取出來
ow.write("你好");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(ow!=null) {
try {
ow.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("end");
}
public static void readFileUseGBK() {
InputStreamReader in=null;
try {
// 創建字節流
// InputStreamReader 是字符流通向字節流的橋梁
// 使用GBK編碼寫入,同時也只能使用GBK格式讀取出來
in=new InputStreamReader(new FileInputStream("E:/gbk.txt"), "GBK");
//in=new InputStreamReader(new FileInputStream("E:/gbk.txt"), "UTF-8");
char[] chs=new char[1024];
int len=-1;
while((len=in.read(chs))!=-1) {
System.out.println(new String(chs,0,len));
// 輸出
// 你好
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("end");
}
}
字符集之間轉換讀取和寫入