定义:字符流是以16位字符为数据单元的IO
一、字符输入流FileReader 【读取文件内容】
/**
* FileReader以字符为单位,读取文件中的内容
* @throws IOException
*/
@Test
public void t1() throws IOException{
//创建并实例化FileReader对象
FileReader fr = new FileReader("Z:\\TestIO\\三国演义第3回.txt");
int i = 0;
String msg = "";
while((i = fr.read()) != -1){
msg += (char)i;
}
System.out.println(msg);
fr.close();
}
二、字符输出流FileWriter 【向文件中写内容】
/**
* FileWriter以字符为单位,向文件中写内容
* @throws IOException
*/
@Test
public void t2() throws IOException{
FileWriter fw = new FileWriter("Z:\\TestIO\\三国演义第4回.txt");
fw.write("既生瑜,何生亮");
fw.close();
}
三、字节缓冲输入流
/**
* BufferedInputStream:字节缓冲输入流
* @throws IOException
*/
@Test
public void t1() throws IOException{
//创建FiliInputStream对象,以字节未单位读取文件内容
FileInputStream fis = new FileInputStream("Z:\\TestIO\\三国演义第5回.txt");
//创建字节缓冲输入流对象BufferInputStream,作用是添加缓冲区,为字节输入流提速(提高读取效率)
BufferedInputStream bis = new BufferedInputStream(fis,1024); //添加缓冲区
//读取内容
int i;
String msg = "";
while((i = bis.read()) != -1){
msg += (char)i;
}
System.out.println(msg);
fis.close();
bis.close();
}
四、字节缓冲输出流
/**
* BufferedOutputStream:字节缓冲输出流
* @throws IOException
*/
@Test
public void t2() throws IOException{
//创建字节输出流
FileOutputStream fos = new FileOutputStream("Z:\\TestIO\\三国演义第5回.txt");
//创建字节缓冲输入流对象BufferOutputStream,作用是添加缓冲区,为字节输出流提速(提高读取效率)
BufferedOutputStream bos = new BufferedOutputStream(fos,1024);
bos.write("hahahahaha".getBytes());
bos.close();
fos.close();
}
五、字符缓冲输入流
/**
* BufferedReader:字符缓冲输入流
* @throws IOException
*/
@Test
public void t3() throws IOException{
//创建并实例化FileReader对象
FileReader fr = new FileReader("Z:\\TestIO\\三国演义第4回.txt");
//创建字符缓冲输入流对象BufferReader,作用是添加缓冲区,为字符号输入流提速(提高读取效率)
BufferedReader br = new BufferedReader(fr,1024);
String i = "";
String msg = "";
while((i = br.readLine()) != null){
msg += i;
}
System.out.println(msg);
br.close();
fr.close();
}
六、字符缓冲输出流
/**
* BufferedWriter:字符缓冲输出流
* @throws IOException
*/
@Test
public void t4() throws IOException{
FileWriter fw = new FileWriter("Z:\\TestIO\\三国演义第4回.txt");
BufferedWriter bw = new BufferedWriter(fw,1024);
bw.write("既生瑜,何生亮");
bw.newLine(); //换行
bw.write("然后就吐血了");
bw.close();
fw.close();
}
七、换行的方法
readLine:该⽅法是BufferedReader对象提供的⽅法,⽅法返回值是String类型,表⽰每次读取⼀⾏的内容
newLine:该⽅法是BufferedWriter对象提供的⽅法,表⽰向⽂件中写⼊⼀个换⾏符
八、关流操作
先开后关,后开先关。