zoukankan      html  css  js  c++  java
  • IO流实现GBK写入文件然后转换UTF-8

     public static void main(String[] args) throws IOException {
            File file = new File("olol\a.txt");//创建要写入的文件路径文件不存在IO流会自动创建,也可以直接创建
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), "GBK");//创建流使用GBK写入数据
            osw.write("窗前明月光,");
            osw.write("
    疑是地上霜.");
            osw.write("
    举头望明月,");
            osw.write("
    低头思故乡.");
            osw.flush();
            osw.close();
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK");//创建转换流进行读取使用GBk进行读取
            int temp = 0;//记录
            char[] c = new char[600];//采用数组进行保存,数组容量要大一点,优化可以采用集合存然后写入的时候遍历进行循环写入
            while ((temp = isr.read(c)) != -1) {//一次读取一个数组
                System.out.print(new String( c) );//用于查看控制台的数据
            }
            OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("olol\a.txt"), "UTF-8");//创建转换流使用utf进行写入在原来的文件上进行操作
            osw2.write(c);//采用直接写入数组
    
            osw2.flush();
            osw2.close();
            isr.close();
        }
    

    问题;
    不能同时读取和写入否则会把原来的数据进行覆盖写入空数据,必须先进行读取数据保存到容器中然后,在进行写入。

  • 相关阅读:
    B 基因改造
    A 密码锁
    Leetcode(884)-索引处的解码字符串
    Leetcode(885)- 救生艇
    Leetcode(23)-合并K个排序链表
    关于优先队列的总结II
    重载运算符问题
    Leetcode(22)-括号生成
    Leetcode(102)-二叉树的层次遍历
    Leetcode(82)-删除排序链表中的重复元素 II
  • 原文地址:https://www.cnblogs.com/zk2020/p/14148629.html
Copyright © 2011-2022 走看看