IO流
抽象基类 文件流 缓存流
InputStream FileInputStream BufferedInputStream
OutputStream FileOutputStream BufferedOutputStream
Reader FileReader BufferedReader
Writer FileWriter BufferedWriter
转换流
InputStreamReader:将一个字节的输入流转换为字符的输入流
OutputStreamWriter:将一个字符的输出流转换为字节的输出流

FileReader字符流读取文件
@Test
public void test(){//FileReader读取文件
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");//单元测试方法中,文件路径相对于当前module;main方法中路径相对当前工程下
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入,read():返回读入的一个字符,如果达到文件末尾,返回-1
int data ;
while ((data=fr.read())!=-1){
System.out.print((char)data);//一个字符一个字符的读
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//4.流的关闭
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileReader中使用read(char[] cbuf)读入数据
@Test
public void test2(){//FileReader读取文件
FileReader fr = null;
try {
//1.实例化File类的对象,指明要操作的文件
File file = new File("hello.txt");
//2.提供具体的流
fr = new FileReader(file);
//3.数据的读入,read(char[] cbuf):返回每次读入cbuf数组中的字符的个数,如果达到文件末尾,返回-1
char[] cbuf = new char[5];
int len ;
while ((len=fr.read(cbuf))!=-1){
System.out.print(new String(cbuf,0,len));//一此读取5个字符
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//4.流的关闭
try {
if(fr!=null)
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

浙公网安备 33010602011771号