Java Inputstream读取文件乱码问题

新人才开始学习写博客,不喜勿喷。欢迎各位大佬批评指正,感激不敬!

我之前做了10个月C#,后来转Java 自学也有一段时间,有面向对象基础学起基础还是挺快的。今天突然突发奇想,想来操作下Java文件读取(不得不说以前自己都很懒,能百度的东西自己都不愿意自己亲手去做,希望广大码友不要学我,凡事自己多实践)这篇文章主要记录自己在使用Inputstream遇到问题(乱码和字节)废话不多说直接上代码

class ReadFile {
public String readfilebyInputStream(String filePath){
String result="";
File file=new File(filePath);
InputStream inputstream=null;
byte []b=new byte[1024];//接受1024个字节
try {
inputstream=new FileInputStream(file);
int temp;
int length=0;
while((temp=inputstream.read())!=-1) {//每次读取一个字节,存放在byte数组中
b[length]=(byte)temp;
length++;
}
return new String(b,0,length);//将字节转换成String 
}
catch(Exception e) {
e.printStackTrace();
return e.getMessage();
}
finally {
if(inputstream!=null) {
try {
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

}

代码调用:

public static ReadFile filetool=new ReadFile();
public static void main(String[] args) {
System.out.println( filetool.readfilebyInputStream("d:/FileTest/test.txt"));
}

输出内容:

ljflsjafl
asfjliruqwdkaopsj
�ʹ�ʱ�䷢
akdlasjflnf������flaw Iowa��2
42żpsdaksfasjsffas

代码分析:

出现乱码,这是因为 我们自己电脑上的文档默认的GBK格式,而我的.java文件被我默认成utf-8文件,所以出现中文乱码,

return new String(b,0,length)更改为return new String(b,0,length,"GBK")指定编码格式中文完整输出。如下:

ljflsjafl
asfjliruqwdkaopsj
送达时间发
akdlasjflnf发酵素flaw Iowa人2

42偶psdaksfasjsffas

但是还有一种情况也可能会出现乱码 比如我把代码改成如下样子,我把byte数组设置小一点比如11个字节,然后循环利用者这11个字节数组去接受读取的数据,每次读满11个字节就转换成String类型;代码如下

class ReadFile {
public String readfilebyInputStream(String filePath){
String result="";
File file=new File(filePath);
InputStream inputstream=null;
byte []b=new byte[11];//字节数组大小
try {
inputstream=new FileInputStream(file);
int temp;
int length=0;
while((temp=inputstream.read())!=-1) {//每次读取一个字节,存放在byte数组中
//每次读取11个字节,并转换成String
if(length==11) {
result+=new String(b,0,length,"GBK");
length=0;
}

b[length]=(byte)temp;
length++;
}
return result+=new String(b,0,length,"GBK");//退出循环的时候,最后一个字节数组可能并没有11个字节
}
catch(Exception e) {
e.printStackTrace();
return e.getMessage();
}
finally {
if(inputstream!=null) {
try {
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}

}

这个时候输出内容:

ljflsjafl
asfjliruqwdkaopsj
送�锸奔浞�
akdlasjflnf发酵素flaw Iowa人2

42偶psdaksfasjsffas

结论:

依然出现了乱码,这是因为我们中文占用两个字节,比如这样一个文本内容"abcdefghjk胡"前面是10字母,第十一位是中文,其实这个文本占用了12个字节,表面上看占用11个字节而已,最后一个中文"胡"会被分解成两个字节,当我用11个字节去取这个文本的时候,只读取了前面10个字母+一个中文的字节,然后用new String(b,0,length,"GBK")转中文的时候自然就乱码。

你可能感兴趣的:(Java Inputstream读取文件乱码问题)