输入输出流
数据流:
/*
数据流
DataInputStream和DataOutputStream
作用:用于基本数据类型遍历或字符串的读取和写入
*/
@Test
public void test1() throws IOException {
// 写入操作
DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
dos.writeUTF("张麻子");
dos.flush();
dos.writeInt(40);
dos.flush();
dos.writeBoolean(true);
dos.flush();
dos.close();
// 得到的data.txt文件无法直接读取
}
@Test
// 将文件中的变量读入到到内存中
public void test2() throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
// 读取顺序要与写入文件时的顺序一致
String name = dis.readUTF();
int age = dis.readInt();
boolean b = dis.readBoolean();
System.out.println(name+age+b);
dis.close();
}
对象流:
序列化:写入文件中
反序列化:从文件在写入内存中
package ObjectInputOutputStream;
import org.junit.Test;
import java.io.*;
public class ObjectStreamTest {
/*
将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutputStream实现
*/
@Test
public void test() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ObjectStream.txt"));
oos.writeObject(new String("我爱中国!"));
oos.flush();
oos.close();
}
/*
反序列化:将磁盘文件(网络)中的对象还原为内存中的对象
使用ObjectInputStream
*/
@Test
public void test2() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("ObjectStream.txt"));
Object obj = ois.readObject();
System.out.println(obj);
ois.close();
}
}
类的序列化有一定的要求:必须实现以下两个接口之一
static,transient的变量无法序列化
若没有手动加serialVersionUID ,在修改对象后,JVM的UID会相应的改变导致无法反序列化