Java read and write Properties file to solve the problem of Chinese garbled code

Generally, the properties configuration file is used in spring projects, which is directly read by the framework. Of course, you also have to consider the problem of coding.

But now, if you need to use java to directly read and write the properties file, you will find many problems. For example, the coding of my properties file is not UTF-8. Or I didn't even think about it.

For another example, when there are men in the properties file, it is found that the Chinese characters read and written are garbled. In my case, the default code of my computer is GBK, but the code is not set when reading, resulting in the problem.

Let's go directly to the code to see the problem.

Running result: This is only the result of the read content.

The following is the content of the written file.

Well, this picture is a little messy. However, all three operating conditions are shown. Very clear.

Finally, the code also shows how to transform bytes into a character stream with encoding format. You can pay attention to this. I also leave a note.

The update of the above code is a structural adjustment with separate functions. The code looks clear in an instant.

Therefore, the above code is generally not recommended to be practical. You can experience it yourself.

Note: I found this later. I don't know if you have this problem.

I found that the encoding format of the written properties file is not a simple UTF-8, but UTF-8 without BOM format. The evidence can be seen in the figure below:

This opening tool is called Notepad + +. It is estimated that you have this on your computers.

But if you change the encoding format of this file to UTF-8 encoding, the running result will be different.

Continue to see the following figure:

I see an additional small bar "-". I don't know how to explain it for the time being.

At this time, this problem also occurs in the written documents. See the following figure for details:

So, I can't explain this for the time being. be ashamed.... Another problem is that the read attributes are not displayed in the order of the original file. Of course, when writing, they are also out of order. This is still a problem and remains to be solved. When it's solved, leave a link here.

Link: Java code enables orderly reading and writing of properties files

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>