import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class FileReadTest {
private String fileName;
public FileReadTest(String file){
this.fileName=file;
}
//读取带有中文的文件用 FileInputStream(fileName),"UTF-8");这样读取文件就会直接用UTF-8解码,不用再做编码转换。
public void ChineseRead(){
try {
//InputStreamReader 是字节流通向字符流的桥梁,它将字节流转换为字符流.
InputStreamReader in=null;
try {
in = new InputStreamReader(new FileInputStream(fileName),"UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//BufferedReader 由Reader类扩展而来,提供通用的缓冲方式文本读取,将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
BufferedReader read=new BufferedReader(in);
String tmp;
try {
while((tmp=read.readLine())!=null){
System.out.println(tmp);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//FileReader继承了InputStreamReader,但并没有实现父类中带字符集参数的构造函数,所以FileReader只能按系统默认的字符集来解码,
//然后在UTF-8 -> GBK -> UTF-8的过程中编码出现损失,造成结果不能还原最初的字符。
public void codeRead(){
String file="D:/my/code.sh";
try {
//FileReader类从InputStreamReader类继承而来。该类按字符读取流中数据。
BufferedReader read=new BufferedReader(new FileReader(file));
String tmpString;
try {
while((tmpString=read.readLine())!=null){
System.out.println(tmpString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
FileReadTest myfile=new FileReadTest("D:/my/code.sh");
myfile.ChineseRead();
myfile.codeRead();
}
}