装饰设计模式:
通过包装一个类,动态地为它增加功能的一种设计模式
关键在于:
包装类的构造方法中要接收一个被包装类的实例对象,然后再进行“包装”
字节缓冲流BufferedInputStream,BufferedOutputStream就是对inputstream和outputStream的包装
其优点在于,这两个类内部已经定义了一个大小为8192的字节数组,减少了代码量
上面的Example05.java就可以简写为:
class Example06{
public void static main(String[] args){
BuffedInputStream in = new BuffedInputStream(new FileInputStream("D:\BaiduYunGuanjia"));
BuffedOutputStream out = new BuffedOutputStream(new FileOutputStream("D:\新建文件夹");
int len = 0 ;
while((len = in.read())!= -1){
out.write(len);
}
in.close();
out.close();
}
}
字符流:
jdk中提供了字符流(InputStream和OutputStream是字节流)
Reader:BufferedReader,CharArrayReader,InputStreamReader(FileReader),PipedReader
Writer:BufferedWriter,CharArrayWriter,OutputStreamWriter(FileWriter),PrintWriter
reader和writer与inputstream,OutputStream其实差不多,都是利用write()和read()
它们同样有包装类,BufferedReader和BufferuedWriter
bufferedReader有一个重要的方法:readLine()
从此:
(ch = reader.read() )!= - 1
或者:(len = bufferedInputStream.read() ) != -1
或者:(len = inputStream.read(buff))!= -1
变成了
(str = br.readLine() ) != null
关于LineNumberReader:可以获取当前读取的行数
在文件加上行号:
public class Example11 {
public void static main(Sring[] args){
FileReader reader = new FileReader("Example04.java");
FileWriter writer = new FileWriter("copy.java");
LineNumberReader lbreader = new LineNumberReader(reader);
String str;
lbreader.setLineNumber(0);
while(( str = reader.readline() ) != null){
writer.write(lbreader.getLineNumber + ":" +str);
writer.write("\r\n");
}
}
}
转换流:将字节流转换为字符流(只针对文本文件的字节流进行转换,如果是图片音频就会造成数据丢失)
主要就是:InputStreamReader(new FileInputStream)
Example12.java
public class example12 {
public void static main(String[] args){
//主要的是以下三段代码
FileInputStream fis = new FileInputStream("src.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
//对于输出流也是这三段
FileOutputStream fos = new FileOutputStream("des.txt");
OutputStreamReader osr = new OutputStreamReader(fos);
BufferedWriter bw = new BufferedWriter(osr);
String line = null;
while((line = br.readline()) != null){
bw.write(line);
}
}
}
其他io流:
对象io流(ObjectInputStream和ObjectOutputStream)
前提条件是:该对象的类实现了serializable接口
Example13.java
public class Example13 {
public void static main(String[] args){
Person p = new Person("perer",24,male);
FileOutputStream fos = new FileOutputStream("object.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p);
}
}
public class Person implements Serializable {
private String name ;
private int age;
private String sex;
Person(String name, int age, String sex){
super();
this.name = name ;
this.age = age;
this.sex = sex;
}
//有必要的话还可以添加get,set方法(函数的封装)
}
反过来,从object.txt中也可以取出来这个对象,核心代码是:
FileInputStream fis = new FileInputStream("object.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Person p = ois.readObject();
|
|