FileInputStream读中⽂乱码问题FileInputStream读中⽂乱码问题
1、前提
以读取编码是GBK的⽂件为案例,⽂件内容只有中⽂和中⽂符号
2、原因
FileInputStream读中⽂乱码是因为⼀个中⽂对应两个字节存储(负数),也就是说,读取对应中⽂的字节数应该是偶数;⽽英⽂对应⼀个字节存储。FileInputStream每次读取⼀个数组长度的字节时,读取的中⽂字节数可能是奇数,也就是只读到中⽂的⼀半字节,出现乱码。
3、解决⽅法
⼀次读取所有字节,此⽅法不靠谱,因为不确定总字节数。
在输出时进⾏判断,遍历数组判断负数的个数,如果是奇数,说明读取到中⽂的⼀半字节,对数组进⾏扩容再输出;否则正常输出4、代码案例
package 第⼆题;
import java.io.File;
import java.io.FileInputStream;
乱码符号有哪些import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
public class MainTest {
public static void main(String[] args) throws UnsupportedEncodingException {
// 创建File对象
File file = new File("D:\\filetest\\");
FileInputStream fileInputStream = null;
try {
// 新建⼀个FileInputStream对象
fileInputStream = new FileInputStream(file);
// 新建⼀个字节数组
byte[] buf = new byte[2];
// read(buf):此⽅法的返回值就是当前读取的字节个数,将数据读取到buf数组
// 将readLen变量也就是read⽅法的返回值,当此变量等于-1,则读到⽂件末尾
int readLen = -1;
//读取⽂件数据
while ((readLen = ad(buf)) != -1) {
int pos=0;//记录负数的个数
for(byte v:buf)
{
if(v<0)
{
pos++;
}
}
//负数个数为偶数,读取完整,没有读取到半个中⽂
if(pos%2==0)
{
// 将字节数组转换成字符串
String content = new String(buf, 0, readLen);
System.out.print(content);
}else {//负数个数为奇数,读取不完整,会乱码
//再读取下⼀位字节
int ad();
int nextLen=readLen+1;
//字节数组扩容⼀位
buf= pyOf(buf,nextLen);
buf[readLen]= (byte) nextByteValue;
String content=new String(buf,0,nextLen);
System.out.print(content);
/
/奇数,字节补全
//针对数组扩容⼀个字节单元
/*  pyOf(buf, readLen+1);
int ad();
buf[readLen]= (byte) nextByteValue;
String content = new String(buf, 0, readLen);
System.out.print(content);*/
}
}
} catch (FileNotFoundException e) {
// 输出堆栈信息
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// ⽂件输⼊流关闭(释放资源)
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block                e.printStackTrace();
}
}
}
}
5、补充内容