IO流:
Reader reader = new FileReader(File file);
Writer writer = new Writer writer(File file);
InputStream is = new FileInputStream(File file);
OutputStream os = new FileOutputStream(File file);
缓冲流: 属于功能流,用于增强性能,提高功能,提高读写速度.
功能流的使用:功能流包裹节点流. 功能流(节点流)
1. 字节缓冲流
BufferedInputStream和BufferedOutputStream
InputStream is = new BufferedInputStream(new FileInputStream("X:/xxx/xx"))
OutputStream os = new BufferedOutputStream(new FileOutputStream("X:/xxx/xx"))
2. 字符缓冲流
新增方法: String readLine() 读取 一个文本行
void newLine() 写入一个行分隔符
BufferedRead rd = new BufferedReader(new FileReader(“X:/xxx/xx”))
BufferedWriter rw = new BufferedWriter(new FileReader(“X:/xxx/xx”))
3. 对象流
对象流:保留数据+数据类型
使用方式: 对象流包节点流 对象流(节点流)
序列化:将对象的信息状态,变为可存储,可传输的过程
序列化输出流:ObjectOutputStream(OutputStream)
新增方法: void writeObject(Object obj)将指定的对象写入objectOutputStream.
反序列化输入流 ObjectInputStream(InputStream)
注意:
- 不是所有类型的对象都能序列化 实现 java.io.Serializable
- 先序列化后反序列化 写出读入的过程一致
- 不是对象的所有属性都需要序列化 transient
- static不能被序列化
- 如果父类实现了Serializable接口,子类中所有内容都能序列化
- 如果父类没有实现,子类实现了Serializable接口,只能序列化子类中独有的内容
public class ObjectDemo04 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
write("D:/bbb.txt");
read("D:/bbb.txt");
}
//读入对象信息
public static void read(String pathName) throws FileNotFoundException, IOException, ClassNotFoundException{
//流
ObjectInputStream is=new ObjectInputStream(new BufferedInputStream(new FileInputStream(pathName)));
//读
Person obj1=(Person)(is.readObject());
String[] obj2=(String[])(is.readObject());
System.out.println(obj1+"-->"+Arrays.toString(obj2));
//关闭
is.close();
}
//写出对象信息
public static void write(String pathName) throws FileNotFoundException, IOException{
//构建流
ObjectOutputStream wr=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(pathName)));
Person p=new Person("李毅",25,"hehe");
String[] arr={"呵呵","哈哈"};
//写出
wr.writeObject(p);
wr.writeObject(arr);
p.setName("老裴");
p.haha="lllllllllll";
//刷出
wr.flush();
//关闭
wr.close();
}
}
class Person implements Serializable{
private String name;
private transient int age;
static String haha="123345";
public Person() {
// TODO Auto-generated constructor stub
}
public Person(String name, int age,String haha) {
super();
this.name = name;
this.age = age;
this.haha=haha;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ","+age+","+haha+"]";
}
}