一、InputStreamReader可以以指定编码来读取文件内容,可以防止乱码。
例:现eclipse编码为GBK,以GBK编码来读取目标文件
package io.byteput;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class InputStreamReaderDemo {
public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
File file=new File("F:"+File.separator+"student.txt");
/*try {
InputStream in=new FileInputStream(file);
byte[] b=new byte[in.available()];
in.read(b);
System.out.println(new String(b));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
InputStreamReader inReader=new InputStreamReader(new FileInputStream(file), "GBK");
int a=0;
try {
while((a=inReader.read())!=-1){
System.out.println((char)a);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}