Unit 12 Streams, files and persistence Flashcards

1
Q

Streams, files and persistence:

What does it mean by “making information persistent” .

A

so that information can be stored at one time and retrieved unchanged at a later time. For example, if you are word processing a document, you expect to be able to save it one day then open it the next day and find it in the same state as you left it. Persistence involves saving data to files

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

Streams, files and persistence:

Files or Streams (fill in the blanks):

_____ are used to store data on an external storage device, such as a hard disk drive.

_____ are a way of transferring data from one place to another in a software system.

A

Files are used to store data on an external storage device, such as a hard disk drive.

Streams are a way of transferring data from one place to another in a software system.

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

Streams, files and persistence:

which is the source and which is the sink?

A

When we want to read data into a Java program, the source is the file and the sink is the Java program. The Java program reads data from the stream

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

Streams, files and persistence:

which is the source and which is the sink?

A

When we want to save data that is currently in a Java program to a file, the source is the Java program and the sink is the file. The Java program writes data to the stream

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

Streams, files and persistence:

Reading from (or writing to) a stream is done sequentially. What does sequentially means?

A

when you read data from a stream the first item is read first, then the second item is read, and so on until the last item is reached.

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

Streams, files and persistence:

Which of these is a Reader/Writer and which is the InputStream/OutputStream class

  1. Instances of subclasses of these classes handle 16-bit character streams. This means they correctly handle textual information based on characters and strings.
  2. Instances of subclasses of these classes handle (8-bit) byte streams. They are used when making objects persistent through a technique called serialisation*, for writing binary data such as sounds and images and internet-based communication.

* The process of converting an object to a sequence of bytes is known as serialisation

A
  1. Reader and Writer classes handle 16-bit character streams
  2. InputStream andOutputStream classes handle (8-bit) byte streams
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

The File class:

File pathnames can be absolute or relative. Which is which, in the examples below

  1. String pathname = “C:/BlueJ/README.TXT”;
  2. OUFileChooser.setPath(“C:/Users/myName/Documents/M250/Activities/Unit12/Unit12_Project_1”);
  3. File aFile = new File (“Documents/M250/Activities/Unit12/Unit12_Project_1”);
A
  1. Absolute - absolute pathname contains all the information you need to know about the location of a file and always starts from the root directory of the disk, usually C:\ in Windows
  2. Absolute
  3. Relative - relative pathname assumes the current working directory as the starting point
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

The File class:

You must remember that both the getFilename() methods

String pathname = “C:/BlueJ/README.TXT”; &

String pathname = OUFileChooser.getFilename();

only return strings, and a further step is needed before we have something that can actually refer to a file. The next step is to create an instance of the Fileclass, and we do this by using the string returned by a getFilename()method as the argument to the File class constructor:

String pathname = //enter code here

File aFile = //enter code here

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

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

The File class:

a File object does hold important information, for example:

  • the pathname;
  • whether the pathname identifies a file or a folder (directory);
  • whether a physical file exists at that pathname;
  • if a physical file exists, whether it can be written to.

Therefore, the protocol of File objects includes the following messages:

  1. _____( ) – returns true if the file or directory denoted by the pathname exists, false otherwise;
  2. _____( ) – returns true if the file denoted by the pathname exists and is a file, false otherwise;
  3. _____( ) – returns true if the file denoted by the pathname exists and is a directory, false otherwise;
  4. _____( ) – returns true if the file denoted by the pathname exists and the current program is allowed to write to that file, false otherwise.
A
  1. exists( )
  2. isFile( )
  3. isDirectory( )
  4. canWrite( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

The File class:

  1. Use the setPath() method to set the path to C:/Users/myName/Documents/M250/Activities/Unit12/Unit12_Project_1.
  2. Get the pathname of a file called README.TXT using thegetFileName() method.
  3. Create a File object using the pathname obtained in step 1.
  4. Using an if statement, test whether the new file object is associated with an actual physical file on disk by sending it an exists() message. If the file does exist, use an alert dialogue box to display the message, ‘A physical file exists!’ If no physical file exists, use an alert dialogue box to display the message, ‘No physical file exists!’
A

OUFileChooser.setPath(“C:/Users/myName/Documents/M250/Activities/Unit12/Unit12_Project_1”);

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

if (aFile.exists( ))

{

OUDialog.alert(“A physical file exists!”);

}

else

{

OUDialog.alert(“No physical file exists!”);

}

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

The File class:

Thinking back to what you learnt in Unit 8, when you execute the statement

File aFile = new File(pathname);

and pathname is null do you observe a compilation error or a run-time error?

A

The error is a run-time error, because whether or not an error is thrown depends on the value of pathname at run-time. It is also an example of an unchecked exception, specifically a NullPointerException. We would know that is an unchecked exception because, when the OUWorkspace runs the compiler, the compiler would not insist that we embed the call of the constructor within a try-catch statement.

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

Exceptions, files and streams:

Unit 8 introduced you to different kinds of error and emphasised the need to catch and recover from checked exceptions where possible.

Which statement do you use to handle an exception thrown by a method?

A

The try-catch statement is used.

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

Exceptions, files and streams:

A non-existence of a file is a potential problem when reading from files. Suggest some other potential problems of reading from and writing to files.

A

Possible problems include:

  • Trying to overwrite a file that is read-only.
  • Trying to write to a file when there is no space on the disk.
  • Trying to read from a file that has become corrupted – so though it exists, it does not contain the data expected by the program.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Exceptions, files and streams:

Unchecked exceptions should not occur in normal program use, and their occurrence usually indicates that the programmer has failed to take into account a problem that was predictable and should have been guarded against.

Programming errors that can result in unchecked exceptions include:

  • failing to test that an index is within the bounds of an array;
  • dividing a number by zero; and,
  • using null where an object was expected.

In this last case, a test is needed. Can you provide the if statement to ensure the program only runs if the pathname is not null (due to the user clicking cancel or “x”)

A

if (pathname != null)

{

File aFile = new File(pathname);

}

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

Exceptions, files and streams:

How can we tell at once that the FileWriter constructor may throw a checked exception from the following header:

public FileWriter(File file) throws IOException

A

because the header contains a throws clause.

———————————————

public FileWriter(File file) throws IOException

public File (String pathname)

Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

Parameters:

pathname – a pathname string

Throws:

NullPointerException – if the pathname argument is null

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

The FileWriter class:

To write data to a file you need to open an output stream. The simplest Writer class you can use to open an output stream to write text to a file is FileWriter. However, first create a File object to describe a physical file

//write code here = OUFileChooser.getFilename();

//write code here = new File(pathname);

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

17
Q

The FileWriter class:

try

{

FileWriter aFileWriter = new FileWriter(aFile);

//code to write to the file goes here

}

catch (Exception anException)

{

//code to catch any exceptions thrown by the

//FileWriter constructor

}

If the code above does not throw an exception, what does it create?

A

it creates an output stream

18
Q

The FileWriter class:

What is the system output if the following code is executed?

aFileWriter.write(72);

aFileWriter.write(‘e’);

aFileWriter.write(‘l’);

aFileWriter.write(‘l’);

aFileWriter.write(‘o’);

aFileWriter.write(System.getProperty(“line.separator”));

aFileWriter.write(“World”);

A

Hello

World

Remember that Java characters are compatible with the int type. That is why we are able to use characters as actual arguments. In the first message we used the int value 72 to demonstrate that this value is the same as the character ‘H’.

19
Q

The FileWriter class:

Write down the system output from the following code where return strings can be assigned to a variable and then concatenated.

String newLine = System.getProperty(“line.separator”);

aFileWriter.write(“Greetings earthlings.” + newLine);

aFileWriter.write(“Take me to your leader!”);

A

Greetings eathlings.

Take me to your leader!

20
Q

The FileWriter class:

Once the data has been written to the file, the FileWriter stream needs to be closed This is easily done with which message:

aFileWriter._____( );

A

The close( ) message:-

aFileWriter.close( );

21
Q

The FileWriter class:-

fill in the missing code

String pathname = OUFileChooser.______________();

File aFile = new _____(_____);

now place this code within a try-catch statement:

FileWriter aFileWriter = new FileWriter(aFile);

aFileWriter.write(72);

aFileWriter.write(‘e’);

aFileWriter.write(‘l’);

aFileWriter.write(‘l’);

aFileWriter.write(‘o’);

aFileWriter.write(System.getProperty(“line.separator”));

aFileWriter.write(“World”);

_Now close *aFileWriter* and end the try statement_

Now add the catch statement by filling in the blanks

catch (Exception _____)

{

System.out.println(“Error: “ + anException);

}

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

try

{

FileWriter aFileWriter = new FileWriter(aFile);

aFileWriter.write(72);

aFileWriter.write(‘e’);

aFileWriter.write(‘l’);

aFileWriter.write(‘l’);

aFileWriter.write(‘o’);

aFileWriter.write(System.getProperty(“line.separator”));

aFileWriter.write(“World”);

aFileWriter.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

22
Q

The FileWriter class:

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

Now, within a try block, create an instance of FileWriter, then:

a. Using a write() message, write the string “To be or not to be” to the FileWriter stream;
b. Write a line separator to the FileWriter stream;
c. Write the string “That is the question” to theFileWriter stream;
d. Close the FileWriter.

e. Write a catch block to catch any exceptions.

A

try

{

FileWriter aFileWriter = new FileWriter(aFile);

aFileWriter.write(“To be or not to be”);

aFileWriter.write(System.getProperty(“line.separator”));

aFileWriter.write(“That is the question”);

aFileWriter.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

23
Q

The FileReader class:

The simplest Reader class you can use to open an input stream to read characters from a file is the FileReader class. Just as for writing to a physical file, we first need to create a File object to describe the physical file we want to read.

Complete the code:

String pathname = //your code goes here

File aFile = your code goes here

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

24
Q

The FileReader class:

The read() method returns an integer (the int value of the character read from the stream), or -1 if the end of the stream has been reached. If we wish to print the value returned by read() as a character (for example, to the Display Pane) we need to cast the integer into a char. For Example

  • int ch = aFileReader.read();
  • System.out.print((char) ch);

Complete the following code for the FileReader class:-

String pathname = // your code goes here

File aFile = // your code goes here

try

{

FileReader aFileReader = new FileReader(aFile);

int ch = aFileReader.read();

while (ch != -1)

{

System.out.print((char) ch);

ch = aFileReader.read();

}

//code to close aFileReader

}

catch (Exception anException)

{

//code to catch any exceptions thrown

}

A

String pathname = OUFileChooser.getFilename();

File aFile = new File(pathname);

try

{

FileReader aFileReader = new FileReader(aFile);

int ch = aFileReader.read();

while (ch != -1)

{

System.out.print((char) ch);

ch = aFileReader.read();

}

aFileReader.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

25
Q

Buffering and wrapping classes:

you can think of a buffer as a mechanism to even out supply and demand. A program may produce data faster than it can be written to a file on a hard disk. Rather than forcing the program to run more slowly, so that data is produced at the same rate at which it can be written, the program can write the data to a buffer, which holds it temporarily until it can be written to the file.

Sometimes a buffer must be flushed. What does that mean?

A

The buffer’s contents are transferred via an output stream to a sink. This is done so that the buffer does not overflow, or because the output stream is closing and we want to ensure that all the data is removed from the buffer.

26
Q

Buffering and wrapping classes:

As well as providing buffering, the classes BufferedWriter and BufferedReader also define two important and useful methods.

Which method does BufferedReader provide which reads in a whole line of text from the buffer as a string. (Compare this with when we used a FileReader, where we could read only one int value at a time, which we converted to a char.)

A

the method readLine( )

The first readLine( ) message sent to an instance of BufferedReader, before returning the first line of the file, causes the FileReader stream to completely fill the buffer with data from the file, in a single read. Subsequent readLine() messages gradually empty the buffer, and it is not until the buffer is empty that theFileReader needs to refill the buffer with data from the file.

27
Q

Buffering and wrapping classes:

As well as providing buffering, the classes BufferedWriter and BufferedReader also define two important and useful methods.

Which method does BufferedWriter provide which simplifies adding a platform-dependent line break to a text file.

A

the method newLine( )

28
Q

Buffering and wrapping classes:

Using an instance ofBufferedWriter, write the following four lines of text to a new file called poem.txt :

________________________________

Hope is the thing with feathers

That perches in the soul

And sings the tune without the words

And never stops at all

Emily Dickinson, ‘Hope is the thing with feathers’

________________________________

remember to close the file poem.txt.

code to help you

String pathName = //your code goes here

File aFile = //your code goes here

BufferedWriter bufferedFileWriter = null;

try

{

bufferedFileWriter = your code here

//you code to write here

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

finally

{

try

{

//your code here

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

}

A

String pathName = OUFileChooser.getFilename();

File aFile = new File(pathName);

BufferedWriter bufferedFileWriter = null;

try

{

bufferedFileWriter = new BufferedWriter(new FileWriter(aFile));

bufferedFileWriter.write(“Hope is the thing with feathers”);

bufferedFileWriter.write(“That perches in the soul”);

bufferedFileWriter.write(“And sings the tune without the words”);

bufferedFileWriter.write(“And never stops at all”);

bufferedFileWriter.write(“Emily Dickinson, ‘Hope is the thing with feathers’”);

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

finally

{

try

{

bufferedFileWriter.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

}

29
Q

FileWriter, Buffering and Wrapping Classes

If you don’t close() a file, after executing code to write onto the file, is the file empty? if so why was there no data in it when the write statements had been executed?

can you delete it before closing it?

A

You find that after the code has been executed without closing the file, the file is empty. If you try to delete the file you will see an error dialogue box indicating the file is still open.

It may not have surprised you to discover that the file could not be deleted until it had been closed, but why was there no data in it when the write statements had been executed? The answer is that the output is buffered and the characters you have written via the BufferedWriter are still in the buffer. Closing the file flushes any characters remaining in the buffer to the file before it is closed, ensuring that all the information is written.

30
Q

Buffering and wrapping classes:

Reading from a file using a BufferedReader:-

  1. You must wrap an instance of FileReader with an instance of BufferedReader.
  2. You read lines of text from the buffer with readLine() messages that you put within a while loop that terminates when readLine() returns null.
  3. Just as we did with an instance of BufferedWriter, you should close a BufferedReader from atry-catch statement nested within a finally block.

Using an instance of BufferedReader, open a file called poem.txt and print the contents to the Display Pane by completing the following code:

OUFileChooser.setPath(“C:/Users/<username>/Documents/M250/Activities/Unit12/Unit12_Project_1");</username>

String pathname = //code here (“poem.txt”);

File aFile = //code here;

BufferedReader bufferedFileReader = //code here;

try

{

String currentLine;

bufferedFileReader = //code here;

currentLine = bufferedFileReader.readLine();

while (//code here)

{

System.out.println(currentLine); currentLine = bufferedFileReader.readLine();

}

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

finally

{

try

{

//code here to close;

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

}

A

OUFileChooser.setPath(“C:/Users/<username>/Documents/M250/Activities/Unit12/Unit12_Project_1"); </username>

String pathname = OUFileChooser.getFilename(“poem.txt”);

File aFile = new File(pathname);

BufferedReader bufferedFileReader = null;

try

{

String currentLine;

bufferedFileReader = new BufferedReader(new FileReader(aFile));

currentLine = bufferedFileReader.readLine();

while (currentLine != null)

{

System.out.println(currentLine); currentLine = bufferedFileReader.readLine();

}

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

finally

{

try

{

bufferedFileReader.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

}

31
Q

Buffering and wrapping classes:

working with text files in a way that will allow you to make objects (specifically Account objects) persistent. What does it mean by making an object persistent?

A

Saving the state of an object to a file on non-volatile storage, such as a hard disk, in such a way that the file can be read back into memory to recreate that object.

32
Q

Buffered and wrapping classes:

  1. Prompt the user for a file name using a file chooser dialogue box and use the returned pathname to create an instance of the File class - using the variable name accountFile.
  2. Declare a variable of type BufferedWriter named bufferedFileWriter and initialise it to null.
  3. Within a try block, create an instance of BufferedWriter that wraps an instance of FileWriter and assigns it to the variable bufferedFileWriter.
  4. Next, using a write()message to bufferedFileWriter, write to the stream an explanatory heading “Account Details (Holder, Account Number and Balance) “
  5. Follow this with a newLine() message.
  6. Then iterate over the set of accounts referenced by the instance variable accountCollection in a manner similar to this

for (Account eachAccount : accountCollection)

{

System.out.println(eachAccount.getHolder() + “ “ + eachAccount.getNumber() + “ “ + eachAccount.getBalance());

}

  • but instead of sending a println() message to System.out send a write() message to bufferedFileWriter, followed by a newLine() message.
    7. Write a catch block to catch any exceptions.
    8. Write a finally block with a nested try-catch statement to close the BufferedWriter.
A

String pathname = OUFileChooser.getFilename();

File accountFile = new File(pathname);

BufferedWriter bufferedFileWriter = null;

try

{

bufferedFileWriter = new BufferedWriter(new FileWriter(accountFile));

bufferedFileWriter.write(“Account Details “ + “(Holder, Account Number and Balance)”);

bufferedFileWriter.newLine();

for (Account eachAccount : accountCollection)

{

bufferedFileWriter.write(eachAccount.getHolder() + “ “ + eachAccount.getNumber() + “ “ + eachAccount.getBalance());

bufferedFileWriter.newLine();

}

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

finally

{

try

{

bufferedFileWriter.close();

}

catch (Exception anException)

{

System.out.println(“Error: “ + anException);

}

}

33
Q

Buffering and wrapping classes:

simply change the code so that it writes the data to file in CSV format.

try

{

bufferedFileWriter = new BufferedWriter(new FileWriter(accountFile));

for (Account eachAccount : accountCollection)

{

bufferedFileWriter.write(eachAccount.getHolder() + “ “ + eachAccount.getNumber() + “ “ + eachAccount.getBalance());

bufferedFileWriter.newLine();

}

}

A

bufferedFileWriter.write(eachAccount.getHolder() + “,” + eachAccount.getNumber() + “,” + eachAccount.getBalance());

bufferedFileWriter.newLine();

______________________________

‘CSV’ stands for either comma-separated variables or comma-separated values, and we say that each comma delimits neighbouring tokens. So in the line:

John Smith,020,150.0

the tokens are “John Smith”, “020” and “150.0”.

The comma is in fact one of the standard delimiters used in files; for example, spreadsheets can usually be saved as CSV files.

34
Q

Reading a text file using the Scanner class

you might imagine that we would simply use an instance of the BufferedReader class to read a text file saved in CSV format in order to recreate the objects represented by the data in the file. Well we could, and we might, but then we would have to think of how to programmatically chop up each line that was read into the comma delimited tokens. This would be tedious. Fortunately the library java.util provides a class called Scanner that will do all the hard work for us.

From the Scanner class, try to say some constructors and methods that might help you to read a text file in CSV format and split each line into its various tokens.

A

the Scanner class has many constructors.

public Scanner(Readable source)

the BufferedReader class implements the Readable interface, and so this constructor would be useful in conjunction with an instance of BufferedReader.

____________________________

Working with Strings, the following is useful -

public Scanner(String source)

____________________________

public boolean hasNextLine()

It returns true if there is another line in the source (the argument given to the constructor), and false otherwise. Such a method would be useful to control a while loop.

____________________________

The method public String nextLine()

returns the next line in a source. So this method would be useful for getting the next line in a multi-line source such as a File, FileReader or BufferedReader.

____________________________

CSV files use commas to delimit tokens. So the following method looks useful:

public Scanner useDelimiter(String pattern)

It informs a Scanner object about the character(s) used to delimit tokens in the source.

____________________________

The method public boolean hasNext()

returns true if there is another token in the source, so again this looks useful for controlling a while loop.

____________________________

The method public String next()

returns the next token in the source as a string. This looks very promising.

____________________________

Another method that might prove useful is:

public double nextDouble()

It returns the next token in the source as a double, but only if the characters in the token can be interpreted as a double value.

35
Q

Scanner Class

Scanner aScanner = new Scanner(“David Green,010,50.0”);

while (aScanner.hasNext( ))

{

System.out.println(“>” + aScanner.next() + “<”);

}

Note that there are no spaces surrounding the commas in the string argument to the Scanner constructor. Note also how the message-send aScanner.hasNext() is used to control the while loop. The while loop will continue to execute until hasNext() returns false, i.e. when there are no more tokens in the source. Note also how the next() message is used within the while loop to return the next token in the source as a string.

Finally, we used left and right angle brackets to help make clearer in the Display Pane where each token begins and ends.

If you selected and executed the above code, and observed the output in the Display Pane.

  1. How many tokens would be printed to the Display Pane?
  2. What do you think is the default delimiter of a Scanner?

Now alter the code to include the statement aScanner.useDelimiter(“,”); as shown below:

Scanner aScanner = new Scanner(“David Green,010,50.0”);

aScanner.useDelimiter(“,”);

while (aScanner.hasNext())

{

System.out.println(“>” + aScanner.next() + “<”);

}

If you selected and executed the modified code, and observed the output in the Display Pane.

3. How many tokens are printed to the Display Pane this time?

A
  1. Two tokens are printed to the Display Pane. If there are more than two lines of text in yourDisplay Pane, check that you did not include any spaces around the commas in the input text.
  2. The string is split on the basis of the space character. The default delimiter of a Scanner is one or more whitespace characters. Whitespace characters include space, tab and newline characters.
  3. Three tokens are returned; the tokens are now delimited by a comma rather than a space.