IDEA FindBugs异常:Reliance on default encoding

文章讲述了在Java编程中遇到IDEAFindBugs工具提示的Relianceondefaultencoding异常,该异常指出使用FileWriter等类时,默认编码可能导致跨平台问题。解决方案是改用InputStreamReader并指定字符集,如UTF_8,以确保编码的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IDEA FindBugs异常:Reliance on default encoding

IDEA FindBugs 异常
Reliance on default encoding
Found reliance on default encoding: new java.io.FileWriter(String)
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.

意思就是:
FileWriter FileReader 是不带编码格式的,默认使用本机器的默认编码,那么就会因为编码问题产生bug的。

解决方法:只需要将FileReader改成InputStreamReader即可,代码如下

import java.io.*;
import java.nio.charset.StandardCharsets;

public class Reliance {
    public static void main(String[] args) throws IOException {
        /*
            IDEA FindBugs 异常
            Reliance on default encoding
            Found reliance on default encoding: new java.io.FileWriter(String)
            Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.

            意思就是:
            FileWriter FileReader 是不带编码格式的,默认使用本机器的默认编码,那么就会因为编码问题产生bug的。
         */
        //问题代码
        try (FileReader fr = new FileReader("D:\\work.txt");
             BufferedReader bufr = new BufferedReader(fr)) {
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufr.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String content = sb.toString();
            System.out.println(content);
        }

        //解决方法:只需要将FileReader改成InputStreamReader即可,具体如下
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\work.txt"), StandardCharsets.UTF_8);
             BufferedReader bufr = new BufferedReader(isr)) {
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufr.readLine()) != null) {
                sb.append(line).append("\n");
            }
            String content = sb.toString();
            System.out.println(content);
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值