黑马程序员技术交流社区

标题: 字节流转字符流乱码 [打印本页]

作者: ehuashao    时间: 2014-4-1 10:40
标题: 字节流转字符流乱码
本帖最后由 ehuashao 于 2014-4-1 14:14 编辑
  1. public class FileTest {

  2.         public static void main(String[] args) throws Exception {
  3.                 FileInputStream fin = new FileInputStream(new File("f://Demo.txt"));
  4.                 FileOutputStream fout =new FileOutputStream("f://11.txt");               
  5.                 InputStreamReader in = new InputStreamReader(fin);               
  6.                 OutputStreamWriter out = new OutputStreamWriter(fout,"gb2312");
  7.                 int  b;
  8.                 while((b=in.read()) != -1){
  9.                         fout.write(b);
  10.                 }               
  11.                
  12.         }
  13. }
复制代码
对java io流,完全不会啊,自己摸索着写,字节流读入,然后转字符流,输出的中文全是乱码,设置了输出编码为  utf-8依然乱码求解啊。

作者: osully    时间: 2014-4-1 10:55
你先照老师的来
read到一个byte[] 数组里
再输出这个数组

慢慢的就会明白了那个b 是不能直接write的

作者: 一诺千金    时间: 2014-4-1 10:59
本帖最后由 一诺千金 于 2014-4-1 11:03 编辑

package com.itheima;

import java.io.*;

public class Tost {
        

        public static void main(String[] args) throws Exception {
        FileInputStream fin = new FileInputStream(new File("G://demo.txt"));
        FileOutputStream fout =new FileOutputStream("G://11.txt");               
        //InputStreamReader in = new InputStreamReader(fin);     ----------------------------------这里注释掉           
        OutputStreamWriter out = new OutputStreamWriter(fout,"gb2312");
        int  b;
        while((b=fin.read()) != -1){
                fout.write(b);
        }               
               
        }
}你转换了两次,读取流用的默认的和输出流指定的冲突了,默认为当前系统自己的,解析的时候你有用的别的。所以乱了套了

作者: 黄晓鑫    时间: 2014-4-1 11:00
本帖最后由 黄晓鑫 于 2014-4-1 11:09 编辑

:lol:lol:lol
作者: ehuashao    时间: 2014-4-1 11:06
一诺千金 发表于 2014-4-1 10:59
package com.itheima;

import java.io.*;

已解决,谢了。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2