This essay mainly introduces a tool class written in the Java language that converts one file encoding to another and does not change the contents of a file:
By reading the contents of the source file, it is implemented by recoding and decoding by urlencoding.
1 Public classchangefileencoding {2 Public Static intFileCount = 0;3 Public StaticString sourcefileroot = "Replace with source file or source directory to be converted";//the root directory where the files will be converted4 Public StaticString sourcecharset = "GB2312";//Source file Encoding5 Public StaticString targetcharset = "UTF8";//Target file Encoding6 Public Static voidMain (string[] args)throwsIOException {7File Filedir =NewFile (sourcefileroot);8 convert (filedir);9System.out.println ("Total dealed:" + filecount + "Files");Ten } One A Public Static voidConvert (file file)throwsIOException { - //If the file is encoded and converted, write overwrite the original file - if(File.isfile ()) { the //handle only. Java end-of-code files - if(File.getpath (). IndexOf (". Java") = =-1) { - return; - } +InputStreamReader ISR =NewInputStreamReader (NewFileInputStream ( - file), sourcecharset); +BufferedReader br =NewBufferedReader (ISR); AStringBuffer SB =NewStringBuffer (); atString line =NULL; - while(line = Br.readline ())! =NULL) { - //Note Write line breaks -line = Urlencoder.encode (line, "UTF8")); -Sb.append (line + "\ r \ n")); the line break is \ r \ n//windows Platform - } in br.close (); - isr.close (); to +File targetfile =NewFile (File.getpath ()); -OutputStreamWriter OSW =NewOutputStreamWriter ( the NewFileOutputStream (targetfile), targetcharset); *BufferedWriter BW =NewBufferedWriter (OSW); $ //write once in string formPanax NotoginsengBw.write (Urldecoder.decode (sb.tostring (), "UTF8")); - bw.close (); the osw.close (); + ASystem.out.println ("Deal:" +File.getpath ()); thefilecount++; +}Else { - //use recursion to encode each file in the directory that ends in. Java $ for(File subFile:file.listFiles ()) { $ convert (subfile); - } - } the } - Wuyi}
Java file Encoding Auto-conversion tool class