读取各种编码的text文件

本文介绍了一个Java程序,该程序能够识别并读取指定文件的编码格式(如gb2312、UTF-16、Unicode或UTF-8)。通过检查文件头部的特定字节来确定其编码类型,并使用相应的编码方式读取文件内容。

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

public static void main(String[] args) throws IOException {
File file = new File("d:/java思考Unicode big endian.txt");
InputStream inputStream = new FileInputStream(file);
byte[] head = new byte[3];
inputStream.read(head);
String code = "gb2312";
if (head[0] == -1 && head[1] == -2 )
{
code = "UTF-16";
}
if (head[0] == -2 && head[1] == -1 )
{
code = "Unicode";
}
if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
{
code = "UTF-8";
}
System.out.println(code);
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(file), code));
String str="";
String r=br.readLine();
while(r!=null){
str+=r+"\r";
r=br.readLine();
}
System.out.println(str);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值