做工程时候,需要用到utf-8无BOM格式的txt文件,所以写了个转换工具类
大致原理是,UTF-8无BOM开头会多几个字节,这个程序把原本文本保存下来,在开头多写入几个字节,再把源文本写回去
package net.forestpolice.lawsearch.utils; import java.io.*; public class FileUtils { public void turnUTF8withoutBOM(File file, File targetFile) throws IOException { if (!targetFile.exists()) { targetFile.createNewFile(); } BufferedReader br = null; BufferedWriter bw = null; br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8")); int i = 0; String str = ""; while ((str = br.readLine()) != null) { if (i == 0)//读取第一行,将前三个字节去掉,重新new个String对象 { byte[] bytes = str.getBytes("UTF-8"); str = new String(bytes, 3, bytes.length - 3); bw.write(str+"\r\n"); i++; } else bw.write(str+"\r\n"); } br.close(); bw.close(); } }
本文介绍了一个用于转换文件编码的小工具类,该工具能够将普通的UTF-8编码文件转换为UTF-8无BOM格式。通过去除文件开头的特定字节,确保了文本文件能够在各种环境下正确解析。
1807

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



