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     } 
View Code

相关文章:

  • 2022-01-18
  • 2021-08-12
  • 2022-01-21
  • 2022-01-07
  • 2021-11-28
  • 2021-09-14
  • 2022-02-28
  • 2021-05-06
猜你喜欢
  • 2022-01-07
  • 2021-10-08
  • 2021-10-19
  • 2021-11-30
  • 2022-12-23
  • 2021-08-29
相关资源
相似解决方案