How to solve the problem of garbled code by reading and writing files in Java
When reading the file stream, we often encounter the phenomenon of garbled code. Of course, the cause of garbled code cannot be one. Here we mainly introduce the problem of garbled code caused by the file coding format. First of all, make it clear that the concepts and differences between text files and binary files.
Text file is a file based on character coding. Common codes include ASCII coding, Unicode coding, ANSI coding and so on. Binary files are files based on value encoding. You can specify what a value means according to the specific application (such a process can be regarded as user-defined encoding.)
Therefore, it can be seen that text files are basically fixed length encoding (there are also non fixed length encoding, such as UTF-8). Binary files can be regarded as variable length coding, because it is value coding. How many bits represent a value is entirely up to you.
For binary files, you must not use strings, because the system default encoding will be used during string initialization by default. However, binary files can only be read, operated and written by byte stream because custom encoding naturally conflicts with fixed format encoding.
For text files, because the encoding is fixed, as long as the file is parsed in its own encoding format before reading the file, then the bytes are obtained, and then the string is initialized through the specified format, the obtained text will not be garbled. Although the binary file can also obtain its text encoding format, it is inaccurate, so it can not be compared with the same.
The specific operations are as follows:
1) Gets the format of the text file
2) Read the file stream through the encoding format of the file
3) Writes a file in the format specified by the file
4) For binary files with few contents, such as word documents, the following methods can be used to read and write files
The above is the whole content of this article. I hope it will be helpful to your study.