packagestream;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importorg.junit.jupiter.api.Test;/** 流的体系结构: 抽象基类 节点流(或文件流) 缓冲流(处理流的一种)
* 字节输入流 InputStream FileInputStream BufferedInputStream
* 字节输出流 OutputStream FileOutputStream BufferedOutputStream
* 字符输入流 Reader FileReader BufferedReader
* 字符输出流 Writer FileWriter BufferedWriter
*
* 字符流只能处理字符,字节流能处理图片,二进制文件
**/
public classFileReaderWriterTest {
@Testpublic void test() throwsIOException {//1.实例化File类的对象//2.提供具体的流
FileReader fr = null;try{
File file= new File("hello .txt");
System.out.println(file.getAbsolutePath());
File file1= new File("C:\\Users\\ASUS\\Desktop\\JAVAEE\\practice\\IO_FIle\\hello.txt");
System.out.println(file1.getAbsolutePath());
fr= newFileReader(file);//3.数据的读入://read()方法:return一个读入的字符,如果读到结尾则输出-1
intdata;while((data = fr.read())!=-1)
System.out.println((char)data);
}catch(Exception e) {
e.printStackTrace();
}finally{//4.流的关闭操作
try{if(fr != null)
fr.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}//对read()操作升级:使用read的重载方法
@Testpublic voidtestFileReader1() {//2.FileReader流的实例化
FileReader fr = null;try{//1.File
File file = new File("hello.txt");
fr= newFileReader(file);//3.读入的操作//read(buf):返回每次读入buf的字符的个数,如果达到文件尾,返回-1
char [] buf = new char[5];intlen;while((len = fr.read(buf)) != -1) {
String s= new String(buf,0,len);
System.out.println(s);
}
}catch(Exception e) {//TODO Auto-generated catch block
e.printStackTrace();
}finally{try{//4.资源的关闭
if(fr!=null)
fr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}/** 输出操作:对应的File可以不存在的
* 如果不存在,在输出的过程中会自动创建此文件
* 如果存在,则会覆盖此文件
* 但是可以增加第二个参数 true 进行追加*/@Testpublic voidtestFileWriter() {
FileWriter fw= null;try{//1.提出File类的对象,指明写出到的文件
File file = new File("hello1.txt");//2.提供FileWriter的对象,用于数据的写出
fw = newFileWriter(file);//3.写出的操作
fw.write("i have a dream.\n");
fw.write("you have a dream too");
}catch(Exception e) {
e.printStackTrace();
}finally{//4.关闭流
try{if(fw != null)
fw.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}/** 进行文件复制
**/@Testpublic voidtestFileReaderFileWriter() {
FileReader fr= null;
FileWriter fw= null;try{
File sfile= new File("hello.txt");
File ttfile= new File("hello2.txt");
fr= newFileReader(sfile);
fw= newFileWriter(ttfile);char [] buf = new char[5];intlen;while((len = fr.read(buf))!=-1) {
fw.write(buf,0,len);
}
}catch(Exception e) {
e.printStackTrace();
}finally{//4.关闭资源
try{
fw.close();
}catch(IOException e) {
e.printStackTrace();
}try{
fr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}