Java語言提供了讀寫基本數(shù)據(jù)類型和對象的機制,本文將介紹如何在Java中使用這些機制。
Java中讀取基本數(shù)據(jù)類型的方法是使用輸入流讀取,寫入基本數(shù)據(jù)類型的方法是使用輸出流寫入。以下是一個簡單的示例:
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中讀寫對象的原理與讀寫基本數(shù)據(jù)類型的原理類似,只不過要使用對象序列化和反序列化機制來實現(xiàn)。以下是一個簡單的示例:
import java.io.*; public class Test { public static void main(String[] args) { try { // 寫入對象 OutputStream os = new FileOutputStream("object.dat"); ObjectOutputStream oos = new ObjectOutputStream(os); Person person = new Person("張三", 20); oos.writeObject(person); oos.close(); os.close(); // 讀取對象 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; } }
下一篇css圖片橫向排列6