1、将本地的文件转换成另外一种编码输出,主要逻辑代码如下:
1 /** 2 * 将本地文件以哪种编码输出 3 * @param inputfile 输入文件的路径 4 * @param outfile 输出文件的路径 5 * @param code 输出文件的编码 6 * @throws IOException 7 */ 8 public void convert(String inputfile,String outfile,String code) throws IOException { 9 StringBuffer sb = new StringBuffer(); 10 //得到当前文件的编码 11 String ch=getCharset(inputfile); 12 InputStreamReader isr=null; 13 OutputStreamWriter osw =null; 14 //根据当前文件编码进行解码 15 if(ch.equals("UTF8")){ 16 isr= new InputStreamReader(new FileInputStream(inputfile), "UTF-8"); 17 }else if(ch.equals("Unicode")){ 18 isr= new InputStreamReader(new FileInputStream(inputfile), "Unicode"); 19 }else { 20 isr= new InputStreamReader(new FileInputStream(inputfile), "GB2312"); 21 } 22 //将字符串存入StringBuffer中 23 BufferedReader br = new BufferedReader(isr); 24 String line = null; 25 while ((line = br.readLine()) != null) { 26 sb.append(line + "\n"); 27 } 28 br.close(); 29 isr.close(); 30 31 //以哪种方式写入文件 32 if("UTF-8".equals(code)){ 33 osw = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"); 34 }else if("GB2312".equals(code)){ 35 osw = new OutputStreamWriter(new FileOutputStream(outfile), "GB2312"); 36 }else if("Unicode".equals(code)){ 37 osw = new OutputStreamWriter(new FileOutputStream(outfile), "Unicode"); 38 }else{ 39 osw = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"); 40 } 41 BufferedWriter bw = new BufferedWriter(osw); 42 bw.write(sb.toString()); 43 bw.close(); 44 osw.close(); 45 } 46 47 /** 48 * 根据文件路径判断编码 49 * @param str 50 * @return 51 * @throws IOException 52 */ 53 private String getCharset(String str) throws IOException{ 54 BytesEncodingDetect s = new BytesEncodingDetect(); 55 String code = BytesEncodingDetect.javaname[s.detectEncoding(new File(str))]; 56 return code; 57 }