一.分类
1.输入流和输出流.
2.字节流和字符流.
3.节点流和处理流.
二.应用
1.输入流和输出流
a.字节流.
抽像类InputStream,常用子类,FileInputStream.
构造方法: FileInputStream fis = new FileInputStream(String str); //需处理异常,str为要读取的文件的路径 eg: E:/src/from.txt
读取方法: int fis.read(byte[] b, int i, int b) // b为存入读取内容的byte数组,i为偏移量,意为从数组b中哪个下标位开始存储.
b为每次读取的字节数,一般不会大于b.length.返回值为本次读取的字节数,当读到文件末尾时,返回值为 -1.
OutputStream, FileOutputStream
FileOutputStream fos = new FileOutputStream(String str);//需处理异常,str为要写入的文件的路径 eg: E:/src/to.txt
写入方法:void fos.write(byte[] b);
b.字符流
Reader --> FileReader
FileReader fr = new FileReader(String str);//需处理异常,str为要读取的文件的路径 eg: E:/src/from.txt
int fr.read(char[] buffer, int i, int j)// buffer为存入读取内容的byte数组,i为偏移量,意为从数组b中哪个下标位开始存储.j为每次读取的字节数,一般不会大于b.length.
返回值为本次读取的字节数,当读到文件末尾时,返回值为 -1.
Writer -->FileWriter
FileWriter fw = new FileWriter(String str);//需处理异常,str为要写入的文件的路径 eg: E:/src/to.txt
void fw.write(cha[] buffer);
2.节点流、处理流和装饰者模式
a.节点流和处理流的使用
public class IOTest{ public static void main(String[] args){ try{ FileReader fr = new FileReader("D:/from.txt"); BufferReader br = new BufferReader(fr); FileWriter fw = new FileWriter("D:/to.txt"); BufferWriter bw = new BufferWriter(fw); while(true){ //返回值为读取的当前行的字符串,当读取到文件末尾时,返回值为空null. String str = br.readLine(); if(str == null){ break; } void bw.newline(str); } }catch(Exception e){ System.out.println(e); }finally{ try{ fr.close(); fw.close(); }catch(Exception e){ System.out.println(e); } } } }
b.装饰者模式(转下一篇:装饰者模式简单理解)