File Manipulation Flashcards
A class that allows you to open a file for writing. It also allows you to write data to the file using the same print and println methods that you have been using to display data on the screen.
PrintWriter class
The name of the file that you wish to open is passed as a what?
Passed as a string
To where is the name of the file that you wish to open passed to?
To the PrintWriter class’s constructor
Syntax for creating an empty text file named StudentData.txt and establish a connection between it and the PrintWriter object named outputFile
PrintWriter outputFile = new PrintWriter(“StudentData.txt”);
Where will the file named StudentData.txt be created?
PrintWriter outputFile = new PrintWriter(“StudentData.txt”);
The file will be created in the current directory or folder.
TRUE OR FALSE?
When the program is finished writing data to the file, it must close the file.
TRUE
How do you write data to a file using the Print Writer?
outputFile.println(“Jim”)
How can you make the program close the file after it is finished writing data to the file?
outputFile.close();
It is what the program throws when an unexpected event occurs in a Java program.
Exception
What happens when the main method throws an exception?
The program halts and an error message is displayed.
TRUE OR FALSE?
“PrintWriter objects are capable of throwing exceptions.”
TRUE
How do you allow a method to rethrow an exception that has not been dealt with?
Write a throws clause in the method header
Syntax for writing a throws clause in the method header
public static void main(String[] args) throws IOException
What would the output in the StudentData.txt file be?
import java.io*;
public class FileManipulation {
public static void main(String[] args) throws IOException {
PrintWriter outputFile = new PrintWriter(“StudentData.txt”);
outputFile.println(“Jim”);
outputFile.println(“95”);
outputFile.println(“Karen”);
outputFile.println(“98”);
outputFile.println(“Bob”);
outputFile.println(“82”);
outputFile.close();
}
}
Jim
95
Karen
98
Bob
82
What are the 2 basic steps when writing a program that writes data to a file?
- You need the import java.io.* statement at the top section of your program.
- Create a PrintWriter object and pass the name of the file as a string to the constructor