网上参考了资料,见本文末尾。感谢前辈的探索,我在他们基础上,进行了优化调整,并且验证测试稳定后,用在自己项目。不敢独享,特别发布,供同行评议。
GBK转换为UTF8代码如下:
public static boolean GBKfileToUTF8(String filePath) {
// 以GBK格式,读取文件
try {
try (FileInputStream fis = new FileInputStream(filePath);
InputStreamReader isr = new InputStreamReader(fis, "GBK");
BufferedReader br = new BufferedReader(isr)) {
String str;
// 创建StringBuffer字符串缓存区
StringBuilder sb = new StringBuilder();
// 通过readLine()方法遍历读取文件
while ((str = br.readLine()) != null) {
// 使用readLine()方法无法进行换行,需要手动在原本输出的字符串后面加"\n"或"\r"
str += "\n";
sb.append(str);
}
String str2 = sb.toString();
// 以UTF-8格式写入文件,file.getAbsolutePath()即该文件的绝对路径,false代表不追加直接覆盖,true代表追加文件
File file = new File(filePath);
try (FileOutputStream fos = new FileOutputStream(file.getAbsolutePath(), false);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8")) {
osw.write(str2);
osw.flush();
}
}
return true;
} catch (FileNotFoundException e) {
log.debug("FileNotFoundException:" + e.toString());
return false;
} catch (UnsupportedEncodingException e) {
log.debug("UnsupportedEncodingException:" + e.toString());
return false;
} catch (IOException e) {
log.debug("IOException:" + e.toString());
return false;
}
}
测试调用该方法代码如下:
System.out.println("GBKfileToUTF8");
String filePath = "E:\\cheleon\\ServerDataTableAllDataSummary20190603.csv";
boolean result = TpTaskUtil.GBKfileToUTF8(filePath);
参考的URL如下:
https://blog.youkuaiyun.com/weixin_42038771/article/details/80490505
https://blog.youkuaiyun.com/guying4875/article/details/81034022
本文介绍了一种将GBK编码的文件转换为UTF-8编码的方法,通过使用Java编程语言实现,包括读取文件、转换编码并写入新文件的完整流程。此方法已在实际项目中验证稳定。
4951

被折叠的 条评论
为什么被折叠?



