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();
    }
}

Java中将文件转换为无BOM(Byte Order Mark,字节顺序标记)的UTF-8格式保存,可以按照以下步骤操作: 1. **读取原文件**: 使用`FileInputStream`和`BufferedReader`从源文件读取内容。 ```java File inputFile = new File("sourceFile.txt"); InputStream inputStream = new FileInputStream(inputFile); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder contentBuilder = new StringBuilder(); ``` 2. **检查BOM并移除**: 检查文件是否有BOM。如果存在,可以用`CharsetUtil`库(例如Apache Commons Lang)或自定义方式移除。 ```java byte[] bom = {0xEF, 0xBB, 0xBF}; // UTF-8 BOM bytes if(Arrays.equals(contentBuilder.toString().getBytes(), bom)) { contentBuilder.delete(0, bom.length); // 删除BOM } ``` 3. **编码为UTF-8**: 将处理后的文本内容转换为UTF-8字符流。 ```java char[] characters = contentBuilder.toString().toCharArray(); byte[] utf8Content = new String(characters, StandardCharsets.UTF_8).getBytes(StandardCharsets.UTF_8); ``` 4. **写入新文件**: 使用`OutputStreamWriter`将UTF-8内容写入新的文件,设置BOM标志为false避免添加额外的BOM。 ```java File outputFile = new File("outputFile.txt"); try (OutputStream outputStream = new FileOutputStream(outputFile); OutputStreamWriter writer = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8, true)) { writer.write(utf8Content); } catch (IOException e) { e.printStackTrace(); } ``` 5. **关闭资源**: 最后别忘了关闭所有打开的输入流、缓冲读者以及输出流。 ```java reader.close(); inputStream.close(); writer.close(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值