java變更檔的編碼方式與給檔案重新命名

來源:互聯網
上載者:User

變更檔的編碼,要利用第三方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;}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.