Java读取txt文件编码格式

这篇博客介绍了如何使用Java读取txt文件,并特别强调了在读取过程中设置UTF-8编码格式的重要性。通过创建FileInputStream和InputStreamReader对象,然后指定编码为UTF-8,确保正确解析文件内容。

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

File fl=new File("./a.txt");

FileInputStream fis=new FileInputStream(fl);

InputStreamReader isr;

int a = fis.read();

int b = fis.read();
if(a==0xEF&&b==0xBB) { //1 UTF-8

isr=new InputStreamReader(fis,"UTF-8");

} else if(a==0xE6&&b==0xB1) { //2 GBK should use UTF-8
isr=new InputStreamReader(fis,"UTF-8");
} else if(a==0xFE&&b==0xFF){ //3 gb2312
isr=new InputStreamReader(fis,"GB2312");
}else if(a==0xFF&&b==0xFE) { //4 Unicode------
isr=new InputStreamReader(fis,"Unicode");
}else{//ANSI use gbk
isr=new InputStreamReader(fis,"GBK");
System.out.println("Can't detect the encode mode!");
}
fis.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值