如何编写直接保存对象到文件并从文件读取对象的方法
怎么编写直接保存对象到文件并从文件读取对象的方法
package date0524_data流; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class Projict { public static void main(String[] args) { File file = new File("abc.txt"); Student s=new Student("iteye",(byte)19,'m'); s.writeFile(file); s.name="csdn"; s.print(); s.readFile(file); System.out.println("*****************"); s.print(); } } class Student { public String name;//为了测试方便,这里设置属性为public public byte age; public char sex; public Student(String name,byte age,char sex) { this.name=name; this.age=age; this.sex=sex; } public void readFile(File f) { try { FileInputStream fis = new FileInputStream(f); DataInputStream dis=new DataInputStream(fis); name=dis.readUTF(); age=dis.readByte(); sex=dis.readChar(); fis.close(); } catch (Exception e) { e.printStackTrace(); } } public void writeFile(File f) { try { FileOutputStream fos=new FileOutputStream(f); DataOutputStream dos=new DataOutputStream(fos); dos.writeUTF(name); dos.write(age); dos.writeChar(sex); dos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } public void print() { System.out.println("name:"+name); System.out.println("age:"+age); System.out.println("sex:"+sex); } }
代码很简单就不解释了
1 楼
josico
32 分钟前
很明显 这该用序列化 LZ - -!