Java語(yǔ)言提供了讀寫基本數(shù)據(jù)類型和對(duì)象的機(jī)制,本文將介紹如何在Java中使用這些機(jī)制。
Java中讀取基本數(shù)據(jù)類型的方法是使用輸入流讀取,寫入基本數(shù)據(jù)類型的方法是使用輸出流寫入。以下是一個(gè)簡(jiǎn)單的示例:
import java.io.*; public class Test { public static void main(String[] args) { try { // 寫入基本數(shù)據(jù)類型 OutputStream os = new FileOutputStream("data.txt"); DataOutputStream dos = new DataOutputStream(os); dos.writeInt(123); dos.writeDouble(3.14); dos.writeBoolean(true); dos.close(); os.close(); // 讀取基本數(shù)據(jù)類型 InputStream is = new FileInputStream("data.txt"); DataInputStream dis = new DataInputStream(is); int i = dis.readInt(); double d = dis.readDouble(); boolean b = dis.readBoolean(); System.out.println("int: " + i + ", double: " + d + ", boolean: " + b); dis.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java中讀寫對(duì)象的原理與讀寫基本數(shù)據(jù)類型的原理類似,只不過(guò)要使用對(duì)象序列化和反序列化機(jī)制來(lái)實(shí)現(xiàn)。以下是一個(gè)簡(jiǎn)單的示例:
import java.io.*; public class Test { public static void main(String[] args) { try { // 寫入對(duì)象 OutputStream os = new FileOutputStream("object.dat"); ObjectOutputStream oos = new ObjectOutputStream(os); Person person = new Person("張三", 20); oos.writeObject(person); oos.close(); os.close(); // 讀取對(duì)象 InputStream is = new FileInputStream("object.dat"); ObjectInputStream ois = new ObjectInputStream(is); Person p = (Person) ois.readObject(); System.out.println(p.getName() + ", " + p.getAge()); ois.close(); is.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } class Person implements Serializable { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }