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文件输出了乱码,请问这是为什么?谢谢!
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();
}
}
这样指定编码之后就不会有乱码了,你不指定编码的时候是因为写文件的时候可能你文件的编码方式和你打开的时候的编码不一样,就造成了乱码。
这样试试: 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();
}
}