zoukankan      html  css  js  c++  java
  • InputStreamReader/OutputStreamWriter乱码问题解决

    /*

    *InputStreamReader参数charset要跟文件编码格式一致。 InputStreamReader读的时候才不会乱码。

    *OutputStreamWriter参数charset设置编码例如UTF-8。在操作系统打开文件时候也要用相应编码打开才不会乱码。

    *InputStreamReader:读操作时编码要与文件编码一致。OutputStreamWriter写操作时设置编码打开文件时也要以相同编码打开。

    */

    public class Test{

    /*记事本读写

    *写字板编码转化为UTF-8的方式非常简单,用记事本打开文件,文件->另存为->在编码中选择uft-8保存就可以了。

    *注意:666.txt和999.txt文件编码都要是UTF-8编码才能保证读写不会乱码。

    */

    public static void main(String[] args) throws IOException {
    Reader reader = new InputStreamReader(new FileInputStream(new File("e:/666.txt")),"UTF-8");
    Writer writer = new OutputStreamWriter(new FileOutputStream(new File("e:/999.txt")),"UTF-8");
    char[] buffer = new char[1024];
    int len = 0;
    while((len=reader.read(buffer))!= -1){
    System.out.println(new String(buffer,0,len));
    writer.write(buffer, 0, len);
    }
    writer.flush();
    writer.close();
    }

    /*word读写*/

    public static void main(String[] args) throws IOException {
    Reader reader = new InputStreamReader(new FileInputStream(new File("e:/123.doc")),"utf-8");
    Writer writer = new OutputStreamWriter(new FileOutputStream(new File("e:/456.doc")),"utf-8");
    char[] buffer = new char[1024];
    int len = 0;
    while((len=reader.read(buffer))!= -1){
    System.out.println(new String(buffer,0,len));
    writer.write(new String(buffer,0,len));
    }
    writer.flush();
    writer.close();
    }

    /*

    *创建记事本999.txt

    *OutputStreamWriter(FileOutputStream,charset)以UTF-8编码写出,正确写法。

    *问题导致原因:999.txt默认以写字板方式打开就乱码,写字板打开打开的时候解码解错,以UTF-8打开问题解决或者换高级编辑器打开。

    */

    public static void main(String[] args) throws IOException {
    String file = "e:\999.txt";
    String charset = "UTF-8";
    FileOutputStream outputStream = new FileOutputStream(file);
    Writer writer = new OutputStreamWriter(outputStream, charset);
    try {
    writer.write("字符流写乱码。。。");
    } finally {
    writer.close();
    }
    }

    }

  • 相关阅读:
    bzoj 3262: 陌上花开
    hdu 5618 Jam's problem again
    bzoj 1176: [Balkan2007]Mokia
    bzoj 2683: 简单题
    Codevs 1080 线段树练习(CDQ分治)
    bzoj 3223: Tyvj 1729 文艺平衡树
    bzoj 1503: [NOI2004]郁闷的出纳员
    bzoj 1208: [HNOI2004]宠物收养所
    bzoj 1588: [HNOI2002]营业额统计
    bzoj 3224: Tyvj 1728 普通平衡树
  • 原文地址:https://www.cnblogs.com/chenweichu/p/5649381.html
Copyright © 2011-2022 走看看