Unit 12 Streams, files and persistence Flashcards
Streams, files and persistence:
What does it mean by “making information persistent” .
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
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.
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.
Streams, files and persistence:
which is the source and which is the sink?

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

Streams, files and persistence:
which is the source and which is the sink?

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

Streams, files and persistence:
Reading from (or writing to) a stream is done sequentially. What does sequentially means?
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.
Streams, files and persistence:
Which of these is a Reader/Writer and which is the InputStream/OutputStream class
- Instances of subclasses of these classes handle 16-bit character streams. This means they correctly handle textual information based on characters and strings.
- 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
- Reader and Writer classes handle 16-bit character streams
- InputStream andOutputStream classes handle (8-bit) byte streams
The File class:
File pathnames can be absolute or relative. Which is which, in the examples below
- String pathname = “C:/BlueJ/README.TXT”;
- OUFileChooser.setPath(“C:/Users/myName/Documents/M250/Activities/Unit12/Unit12_Project_1”);
- File aFile = new File (“Documents/M250/Activities/Unit12/Unit12_Project_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
- Absolute
- Relative - relative pathname assumes the current working directory as the starting point
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
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
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:
- _____( ) – returns true if the file or directory denoted by the pathname exists, false otherwise;
- _____( ) – returns true if the file denoted by the pathname exists and is a file, false otherwise;
- _____( ) – returns true if the file denoted by the pathname exists and is a directory, false otherwise;
- _____( ) – returns true if the file denoted by the pathname exists and the current program is allowed to write to that file, false otherwise.
- exists( )
- isFile( )
- isDirectory( )
- canWrite( )
The File class:
- Use the setPath() method to set the path to C:/Users/myName/Documents/M250/Activities/Unit12/Unit12_Project_1.
- Get the pathname of a file called README.TXT using thegetFileName() method.
- Create a File object using the pathname obtained in step 1.
- 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!’
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!”);
}
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?
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.
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?
The try-catch statement is used.
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.
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.
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”)
if (pathname != null)
{
File aFile = new File(pathname);
}
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
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
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);
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
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?
it creates an output stream

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”);
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’.
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!”);
Greetings eathlings.
Take me to your leader!
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._____( );
The close( ) message:-
aFileWriter.close( );
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);
}
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);
}
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.
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);
}
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
String pathname = OUFileChooser.getFilename();
File aFile = new File(pathname);
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
}
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);
}