码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-01 11:09:37      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ram   string   bytes   style   知识   strong   sre   17.   convert   

这个课程的参考视频和图片来自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();

 

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

标签:ram   string   bytes   style   知识   strong   sre   17.   convert   

原文地址:https://www.cnblogs.com/Johnsonxiong/p/10204160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!