I am not very familiar with IO operations... Encoding and garbled characters are also unknown... Today I met a requirement to encode a file and return the encoded string, such as the original GBK encoding, to the UTF-8
Here, the BytesEncodingDetect class will not be pasted. It mainly uses the get file encoding format.
At the beginning, I tried to change the encoding method directly in the source file, using URLEncoder and URLDecoder for conversion, but it was delayed. The last character of the Chinese odd number is garbled.
Baidu did not find a solution, so I had to adopt my idea: First read the content of the source file, store it in StringBuffer, then delete the source file, and then create a new file, it is stored in another encoding format.
Check the encoding effect: do not check the effect in eclipse. eclipse only looks at the effect in the form of encoding, so you can view the html file on the browser side and right-click to view the specified encoding-encoding, to determine whether the operation is successful.
Package com. test; import java. io. bufferedReader; import java. io. bufferedWriter; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. inputStream; import java. io. inputStreamReader; import java. io. outputStream; import java. io. outputStreamWriter; import java.net. URLDecoder; import java.net. URLEncoder; public class Transcoding {private BytesEncodingDetect encode = ne W BytesEncodingDetect (); public Transcoding () {}/*** encoding conversion * @ param toCharset the encoding to be converted * @ param path the file path to be converted * @ return * @ throws Exception */public String encoding (String toCharset, string path) throws Exception {File srcFile = new File (path); int index = encode. detectEncoding (srcFile); String charset = BytesEncodingDetect. javaname [index]; // same encoding, no need to transcode if (charset. equalsIgnoreCase (toCharset) {return "Encoding Similarly, no need to convert ";} InputStream in = new FileInputStream (path); BufferedReader br = new BufferedReader (new InputStreamReader (in, charset); StringBuffer sb = new StringBuffer (); string s1; while (s1 = br. readLine ())! = Null) {String s = URLEncoder. encode (s1, toCharset); sb. append (s + "\ r \ n"); // a row + press ENTER} br. close (); srcFile. delete (); // delete the original File // write the File again in the new encoding and return the value File newfile = new File (path); // recreate the original File newfile. createNewFile (); OutputStream out = new FileOutputStream (newfile); OutputStreamWriter writer = new OutputStreamWriter (out, toCharset); BufferedWriter bw = new BufferedWriter (writer); bw. write (URLDecoder. decode (sb. toString (), toCharset); String result = URLDecoder. decode (sb. toString (), toCharset); bw. flush (); // fl to bw in the file. close (); return result ;}}