I'm using a program to analyse my Java code an

2019-06-14 10:09发布

I'm using the FindBug program from Maryland University and it gives me this error.

I've tested my code on numerous platforms and it works, so why is this code bad-practice, and what can I do to improve it?

Screenshot of code

标签: java encoding
4条回答
孤傲高冷的网名
2楼-- · 2019-06-14 10:17

you need to specify the charset

you can use anOutputStreamWriter

fileWriter = new OutputStreamWriter(new FileOutputStream(file),charset);
查看更多
Lonely孤独者°
3楼-- · 2019-06-14 10:18

See the FileWriter documentation: "The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream."

It can be considered bad practice to depend on default character encoding.

查看更多
三岁会撩人
4楼-- · 2019-06-14 10:36

Use FileOutputStream, instead of FileWriter. Which can be wrapped using the OutputStreamWriter, which allows you to pass an encoding in the constructor.

Or else, as said by Jeff, the data won't load correctly.

Example

OutputStream fout = new FileOutputStream("test.txt");  
OutputStream bout = new BufferedOutputStream(fout);  
OutputStreamWriter out = new OutputStreamWriter(bout, "UTF-8");
查看更多
爷的心禁止访问
5楼-- · 2019-06-14 10:38

It's telling you the encoding (how the string is turned into bytes) isn't specified.

If you write a text file in Turkey, and load it up in Uzbekistan then you might get different results. Instead (for example) you could specify the encoding directly by converting the string to bytes yourself using a specified encoding (see String.getBytes for an example).

查看更多
登录 后发表回答