1 今天继续看书
Scanner类的应用
1 package File; 2 import java.util.Scanner; 3 4 public class ScannerDemo { 5 public static void main(String[] args){ 6 Scanner con=new Scanner(System.in); 7 String line=con.nextLine(); 8 int i=con.nextInt(); 9 double d=con.nextDouble(); 10 System.out.println(line); 11 System.out.println(i); 12 System.out.println(d); 13 con.close(); 14 } 15 }
对象序列化
1 package File; 2 import java.io.Serializable; 3 public class Person implements Serializable{ 4 private String name; 5 private int age; 6 public String getName(){ 7 return name; 8 } 9 public void setName(String name){ 10 this.name=name; 11 } 12 public int getAge(){ 13 return age; 14 } 15 public void setAge(int age){ 16 this.age=age; 17 } 18 public String toString(){ 19 return "姓名:"+name+",年龄:"+age; 20 } 21 }
使用ObjectOutputStream将对象写到文件中
1 package File; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.ObjectOutputStream; 5 6 public class ObjectOutputstreamDemo { 7 public static void main(String[] args)throws IOException{ 8 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:/Hello.txt")); 9 Person p=new Person(); 10 p.setAge(20); 11 p.setName("吴征云"); 12 oos.writeObject(p); 13 oos.close(); 14 } 15 }
对象反序列化
1 package File; 2 import java.io.FileInputStream; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 6 public class ObjectInputStreamDemo { 7 public static void main(String[] args)throws IOException,ClassNotFoundException{ 8 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("D:/Hello.txt")); 9 Person p=(Person)ois.readObject(); 10 ois.close(); 11 System.out.println(p); 12 } 13 }
序列化一组对象
1 package File; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.ObjectOutputStream; 5 6 public class ObjectInputStreamDemo2 { 7 public static void main(String[] args)throws IOException{ 8 ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("D:/Hello.txt")); 9 Person p=new Person(); 10 p.setAge(20); 11 p.setName("吴征云"); 12 Person p2=new Person(); 13 p.setAge(20); 14 p.setName("吴征云22"); 15 Person[] ps={p,p2}; 16 oos.writeObject(ps); 17 oos.close(); 18 } 19 }
2 没什么问题
3 明天继续看书