Exercise: Convert file encoding

Convert GBK-encoded text files to UTF-8-encoded text files.

case study

  1. Specify the conversion stream of GBK encoding and read the text file.
  2. Use the UTF-8 encoded conversion stream to write out a text file.

Case realization

  1. Create an InputStreamReader object, pass the byte input stream and the specified encoding table name GBK in the constructor
  2. Create an OutputStreamWriter object, pass the byte output stream and the specified encoding table name UTF-8 in the construction method
  3. Use the method read in the InputStreamReader object to read the file
  4. Use the method write in the OutputStreamWriter object to write the read data to the file
  5. Release resources

GBK encoded file
UTF-8 file to be converted

package com.itheima.demo03.ReverseStream;

import java.io.*;

public class Demo04Test {
    
    
    public static void main(String[] args) throws IOException {
    
    
        InputStreamReader isr = new InputStreamReader(new FileInputStream("GBK格式的文本.txt"), "GBK");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("UTF-8格式的文本.txt"), "UTF-8");
        int len = 0;
        while ((len = isr.read()) != -1) {
    
    
            osw.write(len);
        }
        osw.close();
        isr.close();
    }
}

operation result
File content in UTF-8 format after running

Guess you like

Origin blog.csdn.net/weixin_45966880/article/details/113843041