IDEA FindBugs异常:Reliance on default encoding
IDEA FindBugs 异常
Reliance on default encoding
Found reliance on default encoding: new java.io.FileWriter(String)
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.
意思就是:
FileWriter FileReader 是不带编码格式的,默认使用本机器的默认编码,那么就会因为编码问题产生bug的。
解决方法:只需要将FileReader改成InputStreamReader即可,代码如下
import java.io.*;
import java.nio.charset.StandardCharsets;
public class Reliance {
public static void main(String[] args) throws IOException {
/*
IDEA FindBugs 异常
Reliance on default encoding
Found reliance on default encoding: new java.io.FileWriter(String)
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.
意思就是:
FileWriter FileReader 是不带编码格式的,默认使用本机器的默认编码,那么就会因为编码问题产生bug的。
*/
//问题代码
try (FileReader fr = new FileReader("D:\\work.txt");
BufferedReader bufr = new BufferedReader(fr)) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufr.readLine()) != null) {
sb.append(line).append("\n");
}
String content = sb.toString();
System.out.println(content);
}
//解决方法:只需要将FileReader改成InputStreamReader即可,具体如下
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\work.txt"), StandardCharsets.UTF_8);
BufferedReader bufr = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufr.readLine()) != null) {
sb.append(line).append("\n");
}
String content = sb.toString();
System.out.println(content);
}
}
}