IO——2

    科技2025-04-21  14

    文章目录

    序列化流Properties数据流、转换流

    序列化流

    ObjectOutput,对象的序列化: 将内存中的对象直接写入到文件设备中;ObjectInput,对象的反序列化: 将文件设备中持久化的数据转换为内存对象。ObjectOutputStream:被写入的对象必须实现一个接口:Serializable;ObjectInputStream:读取序列化对象的数据。该方法抛出异常:ClassNotFountException。

    序列化/反序列化,我忍你很久了!

    案例:序列化学生集合信息,并反序列化。 public class StudentTest { public static void main(String[] args) { String path = "student.dat"; addStudent(path); inputStreamStudent(path); } // 反序列化,并循环输出 private static void inputStreamStudent(String path) { try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(path)); List<Student> stus = (List<Student>) inputStream.readObject(); System.out.println("反序列化结果为:"); stus.forEach(student -> { student.show(); }); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private static void addStudent(String path) { String i = null; List<Student> list = new ArrayList<>(); Student stu = null; do { stu = new Student(); Scanner sc = new Scanner(System.in); System.out.print("请录入学生学号:"); stu.setId(sc.nextInt()); System.out.print("请录入学生姓名:"); stu.setName(sc.next()); System.out.print("请录入学生性别:"); stu.setGender(sc.nextInt()); list.add(stu); System.out.print("是否继续添加(y/n):"); i = sc.next(); } while ("y".equals(i)); System.out.println(list.size()); // 序列化保存学生的集合对象 try { ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path)); outputStream.writeObject(list); System.out.println("success=============="); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } } public class Student implements Serializable { private static final long serialVersionUID = -3510737277769843023L; private Integer id; private String name; private Integer gender; // 0代表男;1代表女 public void show(){ String s = null; s = (this.gender == 0)?"男":"女"; System.out.println("Student{" + "id=" + id + ", name='" + name + '\'' + ", gender=" + s + '}'); } }

    Properties

    HashTable一个子类。 存储: k V public class Properties extends Hashtable<Object,Object> // 构造 Properties() // 常用方法 String getProperty(String key) Object setProperty(String key, String value) void load(InputStream inStream) 加载文件数据 读取配置文件的内容。 user.properties (资源文件) private static void demo3() { //使用相对路径加载配置文件数据 //在程序运行中没有src/config这个目录的 程序运行在服务器里面 没有src/config目录 //服务器里面: class文件/资源配置文件 (编译路径下 eclipse: bin idea: out/classes) //目的: 获得编译路径下的资源文件内容 类加载器 ClassLoader(编译路径的根路径) //通过Class 来获得类加载器 Properties properties = new Properties(); try { properties.load(PropertiesDemo.class.getClassLoader().getResourceAsStream("com/javasm/io1/user.properties")); // properties.load(PropertiesDemo.class.getResourceAsStream("../io1/user.properties")); } catch (IOException e) { e.printStackTrace(); } System.out.println(properties); String name = properties.getProperty("user.name"); System.out.println(name); }

    数据流、转换流

    基本了解即可。
    Processed: 0.011, SQL: 8