File Handling Flashcards

1
Q

What package needs to be imported to work with files?

A

java.io.*;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Scanner

A

An inbuilt Java class used for scanning simple text. It can parse primitive types and strings using regular expressions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the 4 main steps taken when a file is used by a program?

A
  1. 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.
  2. 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.
  3. Data is then written to the file or read from the file.
  4. When the program is finished using the file, it must be closed:
    myPrintWriter.close( );
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you check if a file exists before proceeding to write data to it or create a new one?

A

You can use the File class’s boolean exists method:
if ( file.exists( ) )

or

if ( !file.exists( ) )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you read data from a file?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you write to an existing file?

A
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)**;
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why is it important to close the file (i.e. Scanner and/or PrintWriter objects)?

A

The .close( ) methods writes any unsaved data remaining in the file buffer to ensure that all desired output is written to the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Buffer

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Flush

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Read position

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Methods to read data from a file: hasNext( )

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Methods to read data from a file: next( )

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Methods to read data from a file: useDelimiter( )

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Methods to read data from a file: hasNextLine( )

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Methods to read data from a file: nextLine( )

A

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( );

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Methods to read data from a file: nextInt( ) & nextDouble( )​

A

These methods can be used instead of the next( ) method to read numbers instead of strings. Otherwise, you may need to convert them afterwards for further use in your program.

17
Q

Methods to read data from a file: trim( )

A

This can be used on tokens that are parsed from a line of data before calling the nextInt( ) or nextDouble( ) methods since they rely on the input from the String being stripped of white space. For example:
int populationValue = Integer.parseInt(population.trim( ));

18
Q

Methods to read data from a file: split( )

A

The string split() method breaks a given string into tokens based on the delimiter passed in the argument. The delimiter can be a single character (such as a comma, semi-colon, period, @, or space), a multi-character delimiter (such as “ and “), or a regular expression (such as [@.] ) . For example:

// Create a string to tokenize

String str = "my name is laurie";
// Break it into tokens using a space delimiter

String [] tokens = str.split(“ “);

// Display the tokens
for (String token : tokens)
 System.out.println(token);
19
Q

What methods are available from the Character class to classify individual characters that you’re processing?

A
  • isDigit( )
  • isLetter( )
  • isUpperCase( )
  • isLowerCase( )
  • isWhiteSpace( )
20
Q

Methods to write data to a file: print( ) & println( )

A

To write data to a file you can use these methods the same way that you do with a Scanner object to write to the console. For example:
while (in.hasNext())
{
String input = in.next();

System.out.println(input);
}

21
Q

Methods to write data to a file: printf( )

A

You can use this method to format of data being written to a file in order to control the display. By default, this method lines up values to the right-hand side. To specify left alignment, you add a hyphen (-) before the field width:
System.out.printf ( “%-10s%10.2f”, items[i] + “:”, prices[i] );

  • First %-10 formats a left justified string. The string items[i] + “:” is padded with spaces so it becomes ten characters wide. The - indicates that the string is placed on the left, followed by sufficient spaces to reach a width of 10.
  • Next, %10.2f formats a floating-point number, also in a field that is ten characters wide. However, the spaces appear to the left and the value to the right.
22
Q

Whitespace

A

This includes spaces, tab characters, and newline characters.

23
Q

What is the overall process for working with text files?

A
  1. Understand the processing task. One of the most important decisions to make at this stage is determining if you need to store the data or if you can process it on the fly.
  2. Determine which files you need to read and write.
  3. Choose a mechanism for obtaining file names. There are three options:
    • Hardcoding file names (such as testScores.txt)
    • Asking the user ( String inFile = in.nextLine(); )
    • Using command-line arguments for file names
  4. Choose between line, word, and character based input. As a rule of thumb, read lines if the data is grouped in rows or records such as is the case with tabular data. However, if data can be grouped across multiple lines, such as a paragraph of text, then read words. Just keep in mind that you lose all white space when reading words. (Reading characters is rare aside from tasks that require analyzing character frequencies or encryption.)
  5. With line based input, extract the required data. After reading a line of data, you need to extract the data, which is typically done by extracting substrings using the Character.isWhiteSpace and Character.isDigit to find the boundaries of the substrings. If you need to work with any of the substrings as numbers, then the data must be converted from a String using the Integer.parseInt or Double.parseDouble methods.
  6. Use classes and methods to factor out common tasks. Processing input files usually involves a lot of repepitive tasks such as deleting blank lines or extracting numbers from strings. These operations should be isolated from the main code.
24
Q

Format specifier

A

The text in bold below:
System.out.printf ( “%-10s%10.2f”, items[i] + “:”, prices[i] );

A format specifier has the following structure:

  • The first character is a %
  • Next, there are optional flags that modify the format, such as - to indicate left alignment. (See the table below for the most commonly used format flags)
  • Next is the field width (including spaces used for padding), followed by an optional precision for floating-point numbers.
  • The format specifier ends with the format type, such as f for floating-point values or s for strings. (See the table below for the most important format types)
25
Q

Format specifier: format flag

A
26
Q

Format specifier: format type

A
27
Q

Format specifier: examples

A
28
Q

Redirection

A

Linking the input or output of a program to a file instead of the keyboard or display.