代码改变世界

[Java in NetBeans] Lesson 17. File Input/Output.

2019-01-01 05:21  Johnson_强生仔仔  阅读(188)  评论(0编辑  收藏  举报

这个课程的参考视频和图片来自youtube

    主要学到的知识点有:

We want to handle the bad Error. (e.g bad input / bugs in program)

1. File() : A Java representation of a file.

File file = new File("test.txt");

 

2. PrintWriter() : Write to a file. 

  • Write string into the file. 
// Write 2 lines(Johnson, 26) into the test.txt file. (If not exist then create one, otherwise will overwrite it.)
PrintWriter output = new PrintWriter(file);
output.println("Johnson");
output.println("26");
output.close();

 

3. Scanner() : Read from a file. 

  • Read string from the file. 
Scanner input = new Scanner(file);
String name = input.nextLine();
int age = input.nextLine();

 

4. Object Serialization : convert an object into a series of bytes so they can be written to disk 

  • Serialization: Object to Disk
  • Deserialization: Disk to Object
  • In order to use the seialization, we need to add implement Serializable in the class definition (the contens will be in a binary format)
public class Student implements Serializable {
  • FileInputStream & ObjectInputStream

       Read from a file as bytes and deserialize a data input stream back into an object

// deserialize the collection of students
FileinputStream fi = new FileinputSream(file);
ObjectInputStream input = new ObjectOutputStream(fi);
while(input.hasNext()){
    Student s =(Student) input.readObject();
    students.add(s);
}
input.close();// Important when writing a file as operating system will deny other programs access until the file is closed
fi.close();

 

  • FileOutputStream & ObjectOutputStream

       Write to a file as bytes and serialize an object into a data input stream

// serialize the collection of students
FileOutputStream fo = new FileOutputSream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
for(Student s: students){
    output.writeObject(s);
}
output.close();// Important when writing a file as operating system will deny other programs access until the file is closed
fo.close();