Download Question 1: Are the following definition correct

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
COMP 249 - Tutorial #5 - Solution
Files
Question 1: Are the following definitions correct? Discuss Why?
1. Text files are not convenient because they take more disk space than Binary files.
Binary files are more efficient to process than text files. However, text files
represent data in a way that is convenient to read by humans.
2. Binary files stores only primitive types such as Bytes.
Binary files can also store serialized objects in addition to primitive types
3. FileNotFoundException might mean that a file could not be created.
Yes. PrintWriter constructor might through a FileNotFoundException meaning
that the file could not be created for output.
4. We don’t need to close a stream as Java takes care of it.
Although Java will close the file for you when the program ends, it is safest to
close the file with an explicit call to close to avoid corrupting the file.
5. If the method hasNextInt() of the class Scanner return false, then we reached end
of file.
No. hasNextInt() return false either at the end of the file or when a token that is
not an int is reached.
6. nextLong() method of Scanner class through a checked exception
NextLong() throws unchecked exception. (NoSuchElementException, …)
7. ObjectOutputStream are used only to write objects into a file
No. ObjectOutputStream has methods to write objects and primitive types to a
binary file
8. A program cannot write objects of different class type into a same file.
You can mix class type in the same file. However, It is a best practice to store
only data of one class type in any one file. Otherwise you could loose data.
9. An array cannot be serialized if it contains objects that are not serializable
Yes. In order to serialize a class, all its objects should be also serialized because
the system needs to make a deep copy of the array to store it in a binary file.
10. RandomAccessFile class has methods writeDouble, writeObject, readDouble,
and readObject
RandomAccessFile objects cannot write and read objects.
Question 2: Will the following code run in all cases?
try {
PrintWriter outputStream = new PrintWriter("stuff.txt");
}
catch(FileNotFoundException e) {
System.out.println("Error opening the file stuff.txt.");
System.exit(0);
}
outputStream.println("The quick brown fox");
outputStream.println("jumped over the lazy dog.");
outputStream.close();
This code will not even compile as outputStream is a local variable inside a try bloc and
is not accessible from the outside.
Solution:
PrintWriter outputStream = null;
try {
outputStream = new PrintWriter(new "stuff.txt");
}
Question 3: What is the output of this code if
a- “file_name” doesn’t exist?
b- “file_name” doesn’t exist and the disk is full?
PrintWriter output = null;
try {
output = new PrintWriter(file_name);
System.out.println(“File successfully opened”);
}
catch (FileNotFoundException e) {
System.out.println(“Error, File not found”);
}
finally {
output.close();
System.out.println(“In finally”);
}
a- File successfully opened
In finally
b- Error, File not found
NullException and the program will be aborted because output is null.
Solution for b- either remove the finally bloc or test for null
finally {
if (outputStream != null)
outputStream.close();
}
Question 4: Change the following code so that it checks for end of file
aScanner inputStream = null;
String line1, line2;
try {
inputStream = new Scanner(new
FileInputStream("morestuff.txt"));
line1 = inputStream.nextLine( );
line2 = inputStream.nextLine( );
}
catch(FileNotFoundException e) {
System.out.println("File morestuff.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
finally {
if inputStream != null)
inputStream.close();
}
System.out.println("The lines read from the file are:");
System.out.println(line1);
System.out.println(line2);
Solution:
Scanner inputStream = null;
String line1, line2;
try
{
inputStream =
new Scanner(new FileInputStream("morestuff.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File morestuff.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
System.out.println("The lines read from the file is:");
if (inputStream.hasNextLine()) {
line1 = inputStream.nextLine( );
System.out.println(line1);
}
if (inputStream.hasNextLine()) {
line2 = inputStream.nextLine( );
System.out.println(line2);
}
inputStream.close( );
BBufferedReader inputStream = null;
String line1, line2;
try {
inputStream = new BufferedReader (new
FileReader("morestuff.txt"));
line1 = inputStream.readLine( );
line2 = inputStream.readLine( );
}
catch(FileNotFoundException e) {
System.out.println("File morestuff.txt was not found");
System.out.println("or could not be opened.");
System.exit(0);
}
catch(IOException e) {
System.out.println(“Error reading from morestuff2”);
}
finally {
if inputStream != null)
inputStream.close();
}
System.out.println("The lines read from the file is:");
System.out.println(line1);
System.out.println(line2);
Solution
BufferedReader inputStream = null;
String line1, line2;
try
{
inputStream =
new BufferedReader (new FileReader("morestuff.txt"));
line1 = inputStream.readLine( );
if (line1 == null) { //end of file reached
}
line2 = inputStream.readLine( );
if (line2 == null) {//end of file reached
}
}
……
CObjectInputStream inputStream = null;
int n1, n2;
try {
inputStream = new ObjectInputStream (new
FileInputStream("morestuff.data"));
n1 = inputStream.readInt( );
n2 = inputStream.readInt( );
}
catch(FileNotFoundException e) {
System.out.println(“Error reading from morestuff”);
System.out.println("or could not be opened.");
System.exit(0);
}
catch(IOException e) {
System.out.println("Problems with input from
morestuff");
}
finally {
if inputStream != null)
inputStream.close();
}
System.out.println("Numbers read from file:");
System.out.println(n1);
System.out.println(n2);
ObjectInputStream inputStream = null;
int n1, n2;
try
{
inputStream =
new ObjectInputStream (new FileInputStream("morestuff.data"));
try {
n1 = inputStream.readInt( );
n2 = inputStream.readInt( );
}
catch(EOFException e){
System.out.println(“End Of file reached”);
{
inputStream.close( );
{
catch(FileNotFoundException e)
{
System.out.println(“Error reading from morestuff”);
System.out.println("or could not be opened.");
System.exit(0);
}
catch(IOException e)
{
System.out.println("Problems with input from morestuff");
}
System.out.println("Numbers read from file:");
System.out.println(n1);
System.out.println(n2);
Question 5:
Write a serializable class Book. A book object has a name and a price. It is required to
implement accessors, mutators, toString, and equals methods.
Write a class BooksReaderWriter which reads a list of books from a text file “books.txt”,
then serialize (write) the books object into a binary file “books.dat”
Write a driver class to test your classes. The test should follow these steps:
1. Read a text file “books.txt”
2. Serialize the book objects into a binary file “books.dat”
3. Create the books objects by reading from the binary file
4. Output the books objects and test if they have the same information as in the file
“books.txt”
books.txt
Java programming
55.50
C++ programming
52.30
Introduction to file management system
80.55
Welcome to computer world
25.22
How to choose a cell phone
10.55
How to improve your reading skills
26.33
Solution:
import java.io.Serializable;
/**
* Book.java
*
*Class Book has a name and a price
*
*
*/
public class Book implements Serializable
{
private String name;
private double price;
public Book ()
{
name = "";
price = 0;
}
public Book(String name, double price)
{
this.name = name;
this.price = price;
}
public Book(Book otherBook)
{
name = otherBook.name;
price = otherBook.price;
}
public String getName()
{
return name;
}
public void setName(String theName)
{
name = theName;
}
public double getPrice()
{
return price;
}
public void setPrice(double thePrice)
{
price = thePrice;
}
public String toString()
{
return name + " costs
}
" + price;
public boolean equals(Object other)
{
if ( other == null ) {
return false;
} // end of if ()
else if ( this.getClass() != other.getClass() ) {
return false;
} // end of if ()
else {
Book book = (Book)other;
return
(this.getName().equals(book.getName())&&
(this.getPrice() ==
book.getPrice()));
} // end of else
}
}// Book
/**Class BooksReaderWriter
* this class reads a list of books from a text file
* and serialize the books object into a binary file
*/
import java.util.Scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class BooksReaderWriter
{
private String sourceFile;
private String targetFile;
private Scanner inputStream = null;
private ObjectOutputStream outputStream = null;
public BooksReaderWriter(String sourceFile, String
targetFile) throws IOException{
this.sourceFile = sourceFile;
this.targetFile = targetFile;
try
{
inputStream =
new Scanner(new
FileInputStream(sourceFile));
outputStream = new ObjectOutputStream(
new FileOutputStream(targetFile));
//
new Scanner
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening
files.");
System.exit(0);
}
}
public void close() throws IOException{
inputStream.close();
outputStream.close();
}
public void readBooksList()throws IOException{
String name = null;
double price = 0;
Book book;
while (inputStream.hasNextLine( ))
{
name = inputStream.nextLine( ); //read book
title
if (inputStream.hasNextLine()) {
//we read the price of the book
price =
Double.parseDouble(inputStream.nextLine());
//we can use nextDouble() method instead
of nextLine()
}
book = new Book (name, price);
System.out.println("Writing " );
System.out.println(book + " to the binary
file");
outputStream.writeObject(book);
}
this.close();
}
}
import
import
import
import
import
import
java.io.EOFException;
java.io.FileInputStream;
java.io.FileNotFoundException;
java.io.IOException;
java.io.ObjectInputStream;
java.util.Scanner;
/**
*Class Driver
*test the methods of classes Book and BookReaderWriter
*/
public class Driver
{
public static void main(String[] args)throws IOException
{
Scanner scan = new Scanner(System.in);
String textFileName = "books.txt";
String binaryFileName = "books.dat";
BooksReaderWriter bookRW = new
BooksReaderWriter(textFileName, binaryFileName);
bookRW.readBooksList() ;
System.out.println();
System.out.println("At this point, you could open
the binary file and see its content");
System.out.println();
System.out.println("Please Enter any character to
continue");
scan.next();
//Now we will read from the binary file
ObjectInputStream inputStream = null;
Book book;
try
{
inputStream =
new ObjectInputStream(new
FileInputStream(binaryFileName));
while (true){
book = (Book)inputStream.readObject();
System.out.println(book);
}
}
catch(EOFException e)
{
System.out.println("No more books object
found");
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find " +
binaryFileName);
}
catch(ClassNotFoundException e)
{
System.out.println("Problem the class type
of data in "+ binaryFileName);
}
inputStream.close();
System.out.println("End of program.");
}
}
books.dat
’ sr
BookëÔŽ²g PM1 1D priceL
namet Ljava/lang/String;xp@KÀ
t Java programmingsq ~
@J&ffffft C++ programmingsq ~ @T#33333t &Introduction to
file management systemsq ~ @98Që…-¸t Welcome to computer
worldsq ~ @%™™™™št How to choose a cell phonesq ~
@:TzáG® t "How to improve your reading skills
Output:
Writing
Java programming costs 55.5 to the binary file
Writing
C++ programming costs 52.3 to the binary file
Writing
Introduction to file management system costs 80.55 to
the binary file
Writing
Welcome to computer world costs 25.22 to the binary file
Writing
How to choose a cell phone costs 10.55 to the binary
file
Writing
How to improve your reading skills costs 26.33 to the
binary file
At this point, you could open the binary file and see its
content
Please Enter any character to continue
3
Java programming costs 55.5
C++ programming costs 52.3
Introduction to file management system costs 80.55
Welcome to computer world costs 25.22
How to choose a cell phone costs 10.55
How to improve your reading skills costs 26.33
No more books object found
End of program.