public static void main(String[] args) {
try {
FileOutputStream fs = new FileOutputStream("d:\\a.txt");
byte[] b = new byte[]{1,2,3};
for(int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
fs.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
以上代码向a.txt文件输出了乱码,请问这是为什么?谢谢!

解决方案 »

  1.   

     public static void main(String[] args) {
            try {
                FileOutputStream fs = new FileOutputStream("d:\\a.txt");
                byte[] b = new byte[]{1,2,3};
                for(int i = 0; i < b.length; i++) {
                    System.out.println(b[i]);
                }
               fs.write("123".getBytes("utf-8"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
    这样指定编码之后就不会有乱码了,你不指定编码的时候是因为写文件的时候可能你文件的编码方式和你打开的时候的编码不一样,就造成了乱码。
      

  2.   

    输入文件里面的是个byte数组,数组中的数字是字符对应的ascii码,1,2,3的ascii码在文件中就是乱码
      

  3.   

    我猜想楼主的意思是想写入字符"1","2","3"。
    这样试试: public static void main(String[] args) {
            try {
                FileOutputStream fs = new FileOutputStream("d:\\a.txt");
                byte[] b = new byte[]{49,50,51};//1对应的ascii码49,2对应50,3对应51。
                for(int i = 0; i < b.length; i++) {
                    System.out.println(b[i]);
                }
                fs.write(b);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }