1025 PAT Ranking (25分)
阿新 • • 發佈:2020-07-15
按指定格式讀取/寫入檔案
InputStreamReader(InputStream in, String charsetName),
1 /** 2 * 指定格式讀取GBK檔案/寫入UTF-8檔案 3 */ 4 private static void characterIOCharsetTest() { 5 String s = "./resources/dir1/dir11/123.txt";6 File f = new File(s); 7 File f2 = new File("./resources/dir1/dir11/123-CharsetCopy.txt"); 8 StringBuilder sb = new StringBuilder(); 9 10 //f是GBK格式檔案,所以以GBK格式的InputStreamReader讀取,再被BufferedReader包裝一層 11 try (BufferedReader gbkReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK"));) {12 String line; 13 while ((line = gbkReader.readLine()) != null) { 14 sb.append(line); 15 //因為line不包含最後的換行符,所以要手動加上去 16 sb.append("\n"); 17 } 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 //f2是目的檔案,以UTF-8格式儲存,所以以UTF-8格式的OutputStreamWriter寫入,被BufferedWriter包裝一層22 try (BufferedWriter utf8Writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "UTF-8"))) { 23 utf8Writer.write(sb.toString()); 24 } catch (IOException e) { 25 e.printStackTrace(); 26 } 27 28 }
整合版本
1 /** 2 * 整合版 3 * 相當於將GBK格式的檔案轉換到UTF8格式的檔案 4 */ 5 private static void characterIOCharsetTest2() { 6 String s = "./resources/dir1/dir11/123.txt"; 7 File f = new File(s); 8 File f2 = new File("./resources/dir1/dir11/123-CharsetCopy.txt"); 9 //f是GBK格式檔案,所以以GBK格式的InputStreamReader讀取,再被BufferedReader包裝一層 10 //f2是目的檔案,以UTF-8格式儲存,所以以UTF-8格式的OutputStreamWriter寫入,被BufferedWriter包裝一層 11 try (BufferedReader gbkReader = new BufferedReader(new InputStreamReader(new FileInputStream(f), "GBK")); 12 BufferedWriter utf8Writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f2), "UTF-8"))) { 13 String line; 14 while ((line = gbkReader.readLine()) != null) { 15 //因為line不包含最後的換行符,所以要手動加上去 16 utf8Writer.write(line + "\n"); 17 } 18 } catch (IOException e) { 19 e.printStackTrace(); 20 } 21 }