java存储以及读取数据主要采用流的方式,分为字符流和字节流。
//存储数据
FileOutputStream fileOutputStream = new FileOutputStream("F:\\test2.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
Student student1 = new Student("张三", 20);
Student student2 = new Student("李四", 19);
objectOutputStream.writeObject(student1);
objectOutputStream.writeObject(student2);
objectOutputStream.close();
//读取数据
FileInputStream fileInputStream = new FileInputStream("F:\\test2.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Object one = objectInputStream.readObject();
Object twObject = objectInputStream.readObject();
Student sone = (Student)one;
Student stwo = (Student)twObject;
System.out.println("name: "+sone.getName()+" age:"+sone.getAge());
System.out.println("name: "+stwo.getName()+" age:"+stwo.getAge());
//存储数据
FileWriter fileWriter = new FileWriter("F:\\file1.txt");
fileWriter.write("hello");
fileWriter.close();
//读取数据(采用缓冲区)
FileReader fileReader = new FileReader("F:\\file1.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String txt = null;
while((txt=bufferedReader.readLine())!=null){
System.out.println(txt);
}
bufferedReader.close();
fileReader.close();