java中按字节读取中文出现乱码,为什么

来源:百度知道 编辑:UC知道 时间:2024/09/23 07:33:10
try {
FileInputStream f = new FileInputStream("f:\\test\\test.txt");

int byteRead = f.read();
while (byteRead!=-1) {

System.out.print((char)byteRead);
byteRead = f.read();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileInputStream f = new FileInputStream("f:\\test\\aa.txt");
byte[] b=new byte[1024];

int byteRead = f.read(b);
while (byteRead!=-1) {
String x=new String(b,"GBK");
System.out.print(x);
byteRead = f.read(b);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
/&

文档类出现乱码应该是字符编码问题,试下换码咯.文本最好用unicode,读取中文字符用FileReader类.

一个汉字两个字节....f.read();只是读出一个字节 当然有问题了..

try {
FileInputStream f = new FileInputStream("f:\\test\\aa.txt");
int size = f.available();
byte[] b=new byte[size];

f.read(b);
String readString = new String( b );
System.out.println( readString );

f.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

你用这段试试:

try {
BufferedReader br = new BufferedReader(new FileReader("f:\\test\\test.txt"));
String line = "";
String str = "" ;
while((line=br.readLine()) != null) {
str += line ;
}
System.out.print(str) ;
} catch (FileNotFoundException e) {
e.printStac