数据流(DataInputStream,DataOutStream)
/*** 处理流之数据流:DataOutputStream, DataInputStream* 需要将一些数据存到文件中,不想老是查看对应的变量* 可以使用数据流将内存中的变量存起来之后再调出来看看*/@Test//这里记录就没用try-catch了,看着好像不美观public void test() throws Exception {
//正常处理流的创建方式:处理流(节点流(文件))DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("Test926.txt"));//输出:方法writeXxx()dataOutputStream.writeUTF("第三方");dataOutputStream.writeInt(123);dataOutputStream.writeBoolean(true);dataOutputStream.close();//正常处理流的创建方式:处理流(节点流(文件))DataInputStream dataInputStream = new DataInputStream(new FileInputStream("Test926.txt"));//输入:方法readXxx()//必须要按照写出去的顺序读取,调用相应的read方法//不按照顺序读取,会报异常String readUTF = dataInputStream.readUTF();int readInt = dataInputStream.readInt();boolean readBoolean = dataInputStream.readBoolean();//关闭流dataInputStream.close();System.out.println(readUTF + readInt + readBoolean);//第三方123true}
对象流(序列化,ObjectInputStream,ObjectOutputStream)
/*** 处理流之对象流:ObjectOutputStream,ObjectInputStream* 序列化对象,数据,* 输出到文件叫序列化,输入到内存叫反序列化* 方法:writeXxx(),readXxx()* <p>* 对象可序列化的要求:需要实现serializable接口,修改相应版本号,不能序列化static和transient修饰的成员变量* 且保证类的属性都是可序列化的,保证封装性,不能存在没序列化的类的调用(默认基本数据类型可序列化)* static final long serialVersionUID = 42L;(接口中有的),如自定义类没实现接口,不能出现在需要序列化类的属性中* 个人暂时想法是:因为反序列化时需要按照顺序选择相应类型的输出* 就直接每个序列化文件对应一种一样的类型,就不用选择不同类的输出了*/@Test//这里记录就没用try-catch了,看着好像不美观public void test1() throws Exception {
//正常处理流的创建方式:处理流(节点流(文件))ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("Test926序列化.txt"));//输出:方法writeXxx()objectOutputStream.writeUTF("爸爸");objectOutputStream.writeInt(1111);//序列化对象objectOutputStream.writeObject(new Test9261("dd", 22));//关闭流objectOutputStream.close();//正常处理流的创建方式:处理流(节点流(文件))ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File("Test926序列化.txt")));//输入:方法readXxx()//必须要按照写出去的顺序读取,调用相应的read方法//不按照顺序读取,会报异常String readUTF = objectInputStream.readUTF();int readInt = objectInputStream.readInt();//可以将对象强转为string,就可以不调用tostring()Object readObject = objectInputStream.readObject();//关闭流objectInputStream.close();//爸爸 1111 Test9261{name='dd', age=22}System.out.println(readUTF + '\t' + readInt + '\t' + readObject.toString());}
打工类:
/*** 序列化打工类:修改版本常量 public static final long serialVersionUID = 42123L;*/
class Test9261 implements Serializable {
public static final long serialVersionUID = 42123L;private String name;private int age;public Test9261(String name, int age) {
this.name = name;this.age = age;}@Overridepublic String toString() {
return "Test9261{" +"name='" + name + '\'' +", age=" + age +'}';}
}