java IO系统采用装饰器模式,用一些装饰类来装饰输入输出来,提供更强大的IO操作
FilterInputStream(FilterOutputStream)继承自InputStream(Outputstream)
常用装饰类(都继承自FilterInputStream) 功能
DataInputStream(DataOutputStream) 读写基本类型即UTF
BufferedInputStream(BufferedOutputStream) 使用缓冲区
PrintStream继承自Outputstream,用于格式化输出到文本或控制台等
示例:
package test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* DataInputStream继承自FilterInputStream(FilterInputStream继承自InputStream)
* 用来装饰InputStream,提供可移植方式从流读取基本数据类型
* DataOutputStream继承自FilterOutputStream(FilterOutputStream继承自OutputStream)
* 用来装饰OutputStream,提供可移植方式向流写入基本数据类型
* DataInputStream/DataOutputStream可以实现数据的存储与恢复
*/
public class DataInputStreamDemo {
public static void main(String[] args) {
DataOutputStream dataOutStream = null;
try {
dataOutStream = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream("file/aa.data")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {// 写入文件
dataOutStream.writeChar('a');
dataOutStream.writeInt(3);
dataOutStream.writeDouble(5.5);
dataOutStream.writeFloat(3.2f);
dataOutStream.writeUTF("nihaoma");
dataOutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
DataInputStream dataInputStream = null;
try {
dataInputStream = new DataInputStream(new BufferedInputStream(
new FileInputStream("file/aa.data")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {// 读取文件
System.out.println(dataInputStream.readChar());
System.out.println(dataInputStream.readInt());
System.out.println(dataInputStream.readDouble());
System.out.println(dataInputStream.readFloat());
System.out.println(dataInputStream.readUTF());
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package test;
import java.io.FileNotFoundException;
import java.io.PrintStream;
/*
* 继承自FilterOutputStream,其中DataOutputStream处理数据的存储,PrintStream处理显示
* 用于格式化打印
*/
public class PrintStreamDemo {
public static void main(String[] args) throws FileNotFoundException {
// 把数据可视化格式显示到文本文件中
PrintStream printStream = new PrintStream("file/test2.txt");
printStream.println('a');
printStream.println(2);
printStream.println(3.2);
printStream.println("liuhaifang");
printStream.println("刘海房");
// 可视化显示到控制台
printStream = new PrintStream(System.out);
printStream.println("hello java");
}
}