File Handling Flashcards
What package needs to be imported to work with files?
java.io.*;
Scanner
An inbuilt Java class used for scanning simple text. It can parse primitive types and strings using regular expressions.
What are the 4 main steps taken when a file is used by a program?
- Construct a file object:
File myFile = new File(“filename.txt”);
*Note, you can also supply the file path instead of the file name if it’s not located in your Eclipse workspace. - Then the file must be opened. You do this by creating a Scanner or PrintWriter object with the desired file name depending on whether you want to read from or write to the file. In the latter case, you would use:
PrintWriter myPrintWriter = new PrintWriter(myFile);
*Note that if a file with the same name already exists, then it will be emptied before new data is written unless you first construct a FileWriter object in append mode and pass this to the PrintWriter. - Data is then written to the file or read from the file.
- When the program is finished using the file, it must be closed:
myPrintWriter.close( );
How can you check if a file exists before proceeding to write data to it or create a new one?
You can use the File class’s boolean exists method:
if ( file.exists( ) )
or
if ( !file.exists( ) )
How do you read data from a file?
Use a file object to construct a Scanner object that reads from the specified input file: Scanner myReader = new Scanner(myFile);
*Note that you cannot use file names in the constructor of a Scanner object. You must use a File object that references the desired file!
How do you write to an existing file?
1. First, you create an instance of the FileWriter class. To do this you pass two arguments to the constructor, the name of the file and the boolean value “true”: FileWriter myFileWriter = **new FileWriter(myFile, true)**; 2. Next, you create a PrintWriter object, passing the FileWriter object as an argument to the constructor: PrintWriter myPrintWriter = **new PrintWriter(myFileWriter)**;
Why is it important to close the file (i.e. Scanner and/or PrintWriter objects)?
The .close( ) methods writes any unsaved data remaining in the file buffer to ensure that all desired output is written to the file.
Buffer
A buffer is a temporary storage location for holding values that have been produced (for example, characters typed by the user) and are waiting to be consumed (for example, read a line at a time). This is done since writing data to a file, which is typically stored on disk, is usually slow. Java buffers a larger chunk of the data into a separate area of memory, the buffer and as system resources free up, data will be transferred from the buffer to the disk.
Flush
A lot of the inbuilt file writer classes in Java buffer the content to be written before it actually gets written to the destination. The flush command ensures that the buffer gets flushed and everything that was asked to be written does get written at the point of the flush.
Read position
This marks the location of the next item that will be read from a file. When a file is opened, its read position is set to the first item in the file. As subsequent items are read, it advances accordingly.
Methods to read data from a file: hasNext( )
This boolean method returns true if this scanner has another token in its input. Therefore, in order to avoid exceptions, this should be used before the next( ) method to ensure that another string exists before proceeding.
Methods to read data from a file: next( )
This method returns the next string in a file that is delimited by white space. Therefore this can be used to read words from a file.
*Note that white space includes spaces, tab characters, and the newline characters that separate lines.
Methods to read data from a file: useDelimiter( )
Given that the next( ) method returns all characters in the String, you can use this method to read just the words and discard anything that isn’t a letter. To do so, you call the method on your Scanner object:
Scanner myReader = new Scanner(myFile);
myReader.useDelimiter( “[^A-Za-z]+ “ );
*Note that this particular argument sets the character pattern to any sequence of characters other than letters.
You can similarly use this method to read characters from a file one at a time. To do so, you call it on your Scanner object with an empty string:
Scanner myReader = new Scanner(myFile);
myReader.useDelimiter( ““ );
*Now each call to .next( ) will return a string of a single character
Methods to read data from a file: hasNextLine( )
This boolean method returns true if there is another line in the input file. Therefore, in order to avoid exceptions, this should be used before the .nextLine( ) method to ensure that another line exists before proceeding.
Methods to read data from a file: nextLine( )
This method returns an entire line of a file (without the newline character). It is ideal to use when each line corresponds to a data record as it can be taken apart for further processing. You can do so by either breaking the line into parts by analyzing the characters or you can use a Scanner object to read them. You do this by instantiating a Scanner object with a line from the nextLine( ) method:
while( myReader.hasNextLine( ) )
{
String line = myReader.nextLine( );
}
Scanner lineScanner = new Scanner( line );
while( !lineScanner.hasNextInt( ) )
{
String countryName = countryName + “ “ + lineScanner.next( );
}
int countryPopulation = lineScanner.nextInt( );