File I/O Exercises

Test Your Understanding

Module 3 • Lesson 5 of 5
Progress 0 / 10 Questions
1
Concept
What is the main difference between storing data in RAM vs storing data in a file?
RAM is faster but files are more secure
RAM data is temporary (lost when program ends), file data is permanent
Files can only store text, RAM can store any data type
There is no difference, they are the same
2
File Types
Which of the following is a text-based (human readable) file?
.exe (executable program)
.png (image file)
.java (Java source code)
.mp3 (audio file)
3
File Class
What does this code do?
File myFile = new File( "data.txt" );
Creates a new file called "data.txt" on the disk
Opens and reads the contents of "data.txt"
Creates a File object that represents the path "data.txt" (file may or may not exist)
Deletes the file "data.txt" if it exists
4
Paths
Which is an example of a relative path?
C:/Users/Ahmed/Documents/data.txt
/home/ahmed/projects/data.txt
resources/data.txt
D:/MyProject/src/Main.java
5
File Methods
Which method checks if a file exists on disk?
myFile.isFile()
myFile.exists()
myFile.canRead()
myFile.length()
6
Scanner
What exception must be handled when creating a Scanner with a File?
IOException
FileNotFoundException
NullPointerException
No exception needs to be handled
7
Scanner Methods
What is the difference between next() and nextLine()?
next() reads a word (token), nextLine() reads the entire line
next() reads a line, nextLine() reads a word
They are the same, just different names
next() reads integers, nextLine() reads strings
8
PrintWriter
What happens if you create a PrintWriter for a file that already exists?
An error is thrown
New content is appended to the end of the file
The existing file is overwritten (old content is erased)
A new file with a different name is created
9
Buffers
Why is it important to call close() on a PrintWriter?
To delete the file from memory
To ensure buffered data is written to the file on disk
To encrypt the file for security
It's not important, just a good habit
10
Code Analysis
What will be in output.txt after this code runs?
PrintWriter writer = new PrintWriter( "output.txt" ); writer.print("Hello"); writer.println(" World"); writer.print("Java"); writer.close();
Hello World Java (all on one line)
Hello World (line 1), Java (line 2)
Hello (line 1), World (line 2), Java (line 3)
The file will be empty because print doesn't save
Quiz Complete!
0/10
Great effort! Review the explanations above.