public class Student implements java.io.Serializable { private String name; private int age; private String gender; private transient String password; public Student(String name, int age,String gender){ this.name=name; this.age=age; this.gender=gender; } public Student(String name, int age,String gender,String password){ this.name=name; this.age=age; this.gender=gender; this.password=password; } 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; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
import java.io.*; public class SerializableObj { public static void main(String[] args) throws IOException, ClassNotFoundException { ObjectOutputStream oos = null; ObjectInputStream ois=null; try { // 创建ObjectOutputStream输出流 oos = new ObjectOutputStream(new FileOutputStream( "c:\\myDoc\\stu.txt")); Student stu = new Student("安娜", 30, "女","aaaa"); System.out.println("姓名为:"+stu.getName()); System.out.println("年龄为:"+stu.getAge()); System.out.println("性别为:"+stu.getGender()); System.out.println("密码为:"+stu.getPassword()); // 对象序列化,写入输出流 oos.writeObject(stu); //创建ObjectInputStream输入流 ois=new ObjectInputStream(new FileInputStream("c:\\myDoc\\stu.txt")); //反序列化,强转类型 Student stu1=(Student)ois.readObject(); //输出生成后对象信息 System.out.println("姓名为:"+stu1.getName()); System.out.println("年龄为:"+stu1.getAge()); System.out.println("性别为:"+stu1.getGender()); System.out.println("密码为:"+stu1.getPassword()); } catch (IOException ex) { ex.printStackTrace(); } finally { try { if (oos != null) { oos.close(); } if (ois != null) { ois.close(); } }catch (IOException ex) { ex.printStackTrace(); } } } }
public class Test { private String name; public Test(){ this.name="小新"; } public Test(String name){ System.out.println("我是:"+this.name); } public static void main(String[] args) { Test test=new Test("小强"); } }
时间: 2024-10-11 17:30:57