代码案例:
第一个:
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"));
Random random = new Random();
bw.write(random.nextInt(10)+"这是什么情况?");
bw.newLine();
bw.write(random.nextInt(10)+"好害羞啊。。。");
bw.flush();
bw.close();
}
效果如下:
第二个:
public static void main(String[] args) throws FileNotFoundException {
File toInfoFile =null;
OutputStream osInfo = null;
PrintStream psInfo = null;
toInfoFile = new File("bug.log");
osInfo = new FileOutputStream(toInfoFile, true);//true在原文件上追加
psInfo = new PrintStream(osInfo, true);//true自动刷新
psInfo.println("这是什么情况?");
}
然后,网上找帖子改,各种该编码格式,都没用!
最后,自己拷贝Java文件到空文件夹,把文件改成ANSI格式
用javac编译,java Test 执行main,中文可以正常输出到文件
所以,就怀疑是IDEA工具编码Java文件问题,不是代码问题
于是,我打算看下IDEA中的class文件是否乱码导致的。
果然,IDEA工具给我编译的class就是乱码的。
解决办法:
第一种方法:
用maven重新install一次,查看class正常了,那么,执行的时候,就不乱码了!
第二种办法:
File | Settings | Build, Execution, Deployment | Compiler | Java Compiler
设置:-encoding utf-8