实现读写功能,只需要四步就可以了:
1.确定源
首先要明确你的数据是从哪里来的,或者是你要将数据写到哪里。例如,你可能要读取一个文件、从网络接收数据,或者将数据写入到数据库或文件中。
2.打开流
为了读取或写入数据,你需要打开相应的流。例如,如果你要读取一个文件,你会使用FileInputStream
来打开文件流。如果你要写入数据到文件,你会使用FileOutputStream
3.操作流
对已经打开的流进行操作。如果你是从流中读取数据,那么你会使用如read()
等方法。如果你是向流中写入数据,那么你会使用如write()
等方法。
4.关闭流
在完成所有的读取或写入操作后,重要的是要关闭流。这可以确保所有的数据都被正确地刷新到其目标位置(例如,从缓冲区写入到文件),并释放系统资源。在Java中,你可以使用close()
方法来关闭流。
代码实现:
1.Test1:
package a0420.iotest1.iotest1;
import a0420.iotest1.utlixu.SerializableObjectUtile;
import java.io.IOException;
//io!!!!!!!!!!
//1.确定源
//2.打开流
//3.操作流(先读后写)
//4.关闭流
public class Test1 {
public static void main(String[] args) {
//序列
Student s=new Student("张三",18);
try {
SerializableObjectUtile.SerializObject("D://idealTestio//兵马俑",s);
} catch (IOException e) {
e.printStackTrace();
}
//反序列
try {
Object o=SerializableObjectUtile.ReSerializObject("D://idealTestio//兵马俑");
Student s1=(Student) o;
System.out.println(s1.getName());
s1.setName("李四");
System.out.println(s1.getName());
System.out.println(s1.getAge());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2.Student:
package a0420.iotest1.iotest1;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student() {
}
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;
}
}
3.方法:
package a0420.iotest1.utlixu;
import java.io.*;
public class SerializableObjectUtile {
public static void SerializObject(String diskPath,Object obj) throws IOException {
FileOutputStream fos=null;
ObjectOutputStream oos=null;
fos=new FileOutputStream(diskPath);
oos=new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
}
public static Object ReSerializObject(String diskPath) throws IOException, ClassNotFoundException {
FileInputStream fis=null;
ObjectInputStream obs=null;
fis= new FileInputStream(diskPath);
obs=new ObjectInputStream(fis);
Object o=obs.readObject();
obs.close();
fis.close();
return o;
}
}