Java练习 关于IO流 对象 读写的案例

Java练习 关于IO流 对象 读写的案例
方法一:把对象存入文件中进行读写:
package com.io; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; public class Test { public static void main(String[] args) { Student s1 = new Student("刘广法博客", "001"); Student s2 = new Student("网址是:liuguangfa.com", "002"); // 输出(通过文件进行输出) File file = new File("d:/aa.cc"); ObjectOutputStream out = null; ObjectInputStream objin = null; try { file.createNewFile(); OutputStream bout = new FileOutputStream(file); out = new ObjectOutputStream(bout); // 输出过程 out.writeObject(s1); out.writeObject(s2); out.writeObject(null); // 输入 InputStream in = new FileInputStream(file); objin = new ObjectInputStream(in); Object object; while ((object = objin.readObject()) != null) { System.out.println(object); } } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { out.close(); objin.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Java控制台:
Student [nameString=刘广法博客, idString=001]
Student [nameString=网址是:liuguangfa.com, idString=002]
将读写过程分开的过程如下:
/** * 将文件进行对象进行保存 */ public void objFile() { File file = new File("d:/employee"); ObjectOutputStream osObject = null; try { // 判断输出流的文件是否存在 if (!file.canExecute()) { file.createNewFile(); } OutputStream os = new FileOutputStream(file); osObject = new ObjectOutputStream(os); // 输出的过程 for (int i = 0; i < employees.size(); i++) { osObject.writeObject(employees.get(i)); // if (i == (employees.size() - 1)) { // osObject.writeObject(employees.get(i)); // osObject.writeObject(null); // } else { // osObject.writeObject(employees.get(i)); // } } osObject.writeObject(null); osObject.flush(); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { osObject.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 将对象文件读取出来 */ public void readerObjectFile() { File file = new File("d:/employee"); // 判断文件是否存在 if (file.canExecute()) { } // 将文件读取到系统中 ObjectInputStream isObject = null; try { InputStream is = new FileInputStream(file); isObject = new ObjectInputStream(is); Object obj = null; while ((obj = isObject.readObject()) != null) { employees.add((Employees) obj); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { isObject.close(); } catch (IOException e) { e.printStackTrace(); } } }
方法二:把对象存入字符中进行读写:
文章来源:刘广法,转载请注明出处。原文链接网站为:https://liuguangfa.com/