Java将文件转换成UTF-8无BOM格式

做工程时候,需要用到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();
    }
}

猜你喜欢

转载自blog.csdn.net/Lynn_coder/article/details/79954509