Java IO

按指定格式读取/写入文件

关键:InputStreamReader(InputStream in, String charsetName),OutputStreamWriter(OutputStream out, String charsetName)

通过InputStreamReaderOutputStreamWriter,我们可以指定输入/输出流的格式,从而进行文件的格式转换

 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 }

 

 

posted @ 2020-07-15 16:44  细雨轻风  阅读(173)  评论(0编辑  收藏  举报