更改文件的编码,要利用第三方jar包:cpdetector_1.0.10.jar,其中它依赖于jar包:antlr-2.7.4.jar,chardet-1.0.jar,jargs-1.0.jar,
注:jar的下载地址为:http://download.csdn.net/detail/kuangfengbuyi/4658378
获取文件的编码:
1 public static String guessEncoding(String filePath) { 2 CharsetPrinter cp = new CharsetPrinter(); 3 try { 4 String encode = cp.guessEncoding(new File(filePath)); 5 // System.out.println(encode); 6 return encode; 7 } catch (MalformedURLException e) { 8 // TODO Auto-generated catch block 9 e.printStackTrace(); 10 } catch (IOException e) { 11 // TODO Auto-generated catch block 12 e.printStackTrace(); 13 } 14 return null; 15 }
根据指定的编码方式读取文件的内容:
1 public static String read(String filePath,String encode) { 2 String content = ""; 3 try { 4 BufferedReader br = new BufferedReader(new InputStreamReader( 5 new FileInputStream(filePath),encode)); 6 String str = ""; 7 while ((str = br.readLine()) != null) { 8 content += str + "\n"; 9 } 10 br.close(); 11 } catch (UnsupportedEncodingException e) { 12 // TODO Auto-generated catch block 13 e.printStackTrace(); 14 } catch (FileNotFoundException e) { 15 // TODO Auto-generated catch block 16 e.printStackTrace(); 17 } catch (IOException e) { 18 // TODO Auto-generated catch block 19 e.printStackTrace(); 20 } 21 // System.out.println(content); 22 return content; 23 }
以指定的编码写入文件:
1 public static void write(String filePath, String encode, String content) { 2 try { 3 //FileInputStream fis = new FileInputStream(filePath); 4 Writer out = new BufferedWriter(new OutputStreamWriter( 5 new FileOutputStream(filePath), encode)); 6 out.write(content); 7 // System.out.println(content); 8 out.close(); 9 } catch (UnsupportedEncodingException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } catch (FileNotFoundException e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 } catch (IOException e) { 16 // TODO Auto-generated catch block 17 e.printStackTrace(); 18 } 19 }