更改文件的编码,要利用第三方jar包:cpdetector_1.0.10.jar,其中它依赖于jar包:antlr-2.7.4.jar,chardet-1.0.jar,jargs-1.0.jar,
获取文件的编码:
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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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 block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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 block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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;
}