Java IO file code conversion implementation code

  • 2020-04-01 02:37:55
  • OfStack

I really don't know much about IO operation... To code, garbled code is also a half understanding... Today we encountered a requirement to encode a file and return the encoded string, such as the original GBK encoding, to utf-8

The BytesEncodingDetect class is not posted. Mainly used inside the get file encoding format.

At first, I tried to modify the encoding method directly in the source file, using URLEncoder and URLDecoder for conversion, but I failed. The last word of the odd number in Chinese is garbled

Baidu found a solution, all failed, had to adopt my idea is: first read the content of the source file, stored in StringBuffer, and then delete the source file, and then new a file, and then in another encoding form stored in.

View the effect after the encoding: be careful not to view the effect in eclipse, eclipse in a form of encoding to view, so you can view in the browser side such as HTML files, see the specified encoding can right-click - encoding, to judge whether it 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 = new BytesEncodingDetect();
 public Transcoding() {
 }
 
 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 code, no transcoding required
  if (charset.equalsIgnoreCase(toCharset)) {
   return " Same encoding, no conversion required ";
  }

  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+"rn");//One line + enter
  }

  br.close();
  srcFile.delete();//Delete the original file
  //Write the new code back to the file and return the value
  File newfile = new File(path);//Rebuild 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();//Brush it into a file
  bw.close();
  return result;
 }
}


Related articles: