zoukankan      html  css  js  c++  java
  • 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("
    ");
    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 + "
    ");
    17         }
    18     } catch (IOException e) {
    19         e.printStackTrace();
    20     }
    21 }

     

  • 相关阅读:
    fetch API 和 ajax
    java 通过数据库名获得 该数据所有的表名以及字段名、字段类型
    自定义注解,通过反射获得注解中的值(详细自定义注解解释)
    main方法中sleep
    eclipse中设置JVM内存
    命令java 找不到或无法加载主类
    windows下的命令
    mac terminal基本命令
    ThreadLocal 源码剖析
    SQL中的函数用法
  • 原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/13306425.html
Copyright © 2011-2022 走看看