Java 读写GBK编码的文件
   1 分钟阅读    邵晨峰

Java 读写GBK编码的文件

以GBK编码某个读写文件

读入:

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"), Charset.forName("GBK")));
String str = br.readLine();
br.close();

写出:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("a.txt"), Charset.forName("GBK")));
bw.write("hello");
bw.flush();
bw.close();

使用try-with-resource语法确保close被执行

try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream("test.txt"), Charset.forName("GBK"));
       BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream("out.txt", Charset.forName("GBK")))) {
  int b;
  while ((b = bin.read()) != -1) {
    bout.write(b);
  }
}
catch (IOException e) {
  e.printStackTrace();
}

查看系统默认字符集

Charset c = Charset.defaultCharset();
System.out.println(c.name());

输出所有的支持字符集

SortedMap<String, Charset> sm = CharsetavailableCharsets();  
Set<String> keyset = sm.keySet();  
System.out.println("Java 支持的所有字符集";  
for (String s : keyset) {  
    System.out.println(s);  
}

字符编码互转

String a = "我是中国人";		
		
String b = new String(a.getBytes("UTF-8"), "GBK");
System.out.println(b);
		
String c = new String(b.getBytes("GBK"), "UTF-8");
System.out.println(c);