變更檔的編碼,要利用第三方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
擷取檔案的編碼:
public static String guessEncoding(String filePath) {CharsetPrinter cp = new CharsetPrinter();try {String encode = cp.guessEncoding(new File(filePath));// System.out.println(encode);return encode;} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}
根據指定的編碼方式讀取檔案的內容:
public static String read(String filePath,String encode) {String content = "";try {BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),encode));String str = "";while ((str = br.readLine()) != null) {content += str + "\n";}br.close();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}// System.out.println(content);return content;}
以指定的編碼寫入檔案:
public static void write(String filePath, String encode, String content) {try {//FileInputStream fis = new FileInputStream(filePath);Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), encode));out.write(content);// System.out.println(content);out.close();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
同時附帶記一下檔案的重新命名:
此處代碼沒有可重用性,主要是針對歌詞檔案的重新命名,
本來的格式是:歌手- 歌名.lrc,然後我的修改的格式為:歌名-歌手.lrc
public static void rename(File file) {// file.getParent()System.out.println(file.getName());String fileFormat = file.getName().split("\\.")[1].trim();String[] fullname = file.getName().split("\\.")[0].split("-");String result = fullname[1].trim() + "-" + fullname[0].trim() + "."+ fileFormat;String fullRet = file.getParent() + "\\" + result;File reFile = new File(fullRet);if (file.renameTo(reFile)) {System.out.println(reFile.getName());}// return result;}