Description
1) Create a Lab2 folder for this project
2) Use the main driver program (called Writers.java) that I provide below to write files of differing types. You can copy and paste this code, but make sure the spaces variable copies correctly. The copy and paste operation eliminates the spaces between the quotes on some systems.
3) In the writers program, fill in the code for the three classes (Random, Binary, and Text). In each class, you will need a constructor, a write method, and a close method. The constructor opens the file, the write method writes a record, and the close method closes the file.
4) Other than what I just described, don't change the program in any way. The program asks for a file type (random, binary, or text) and the name of the file to create. In a loop it inputs a person's name (string), a person's age (int), and a person's annual salary (double). It writes to a file of the appropriate type. The loop terminates when the user indicates that inputting is complete. The program then asks if another file should be created. If the answer is yes, the whole process starts again. This and all of the java driver programs should be saved in your lab2 folder but not in the cs258 sub-folder.
5) Note: The method signatures for accessing all of the three types of files (binary, random, and text) are on the class web-site. Go to power point slides and click on week two. This will help if you didn't take accurate notes in class.
6) Write a main program to read binary files (BinReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program.
7) Write a main program to read random files (RandReader.java). This program only needs to be able to read and display records from a Binary file that was created by the writers program. Make sure that this program reads and displays records in reverse order. DO NOT USE AN ARRAY!!!
8) In your Lab2 folder, create a subfolder within lab2 named cs258. Download Keyboard.java from the class web-site to that folder. Add a new first line of Keyboard.java with the statement, package cs258;. This line will make Keyboard.java part of the cs258 package. The driver program shown below has an import ‘cs258.*;’ statement to access the java files in this package.
9) Modify Keyboard.java. We want to extend this class so it can be extended to allow access to multiple files. The changes follow:
a. Remove all static references. This is necessary so that there will be an input stream variable (in) in each object.
b. Change the private modifier of the in and current_token variables to protected. Change the private modifier to protected in all of the signature lines of the overloaded getNextToken methods.
c. Create a constructor that instantiates the input stream for keyboard input. Remove the instantiation from the original declaration line for the in variable. The constructor doesn't need any parameters.
10)Create a class TextR.
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Description 1) Create a Lab2 folder for this project2.docx
1. Description
1) Create a Lab2 folder for this project
2) Use the main driver program (called Writers.java) that I
provide below to write files of differing types. You can copy
and paste this code, but make sure the spaces variable copies
correctly. The copy and paste operation eliminates the spaces
between the quotes on some systems.
3) In the writers program, fill in the code for the three classes
(Random, Binary, and Text). In each class, you will need a
constructor, a write method, and a close method. The
constructor opens the file, the write method writes a record, and
the close method closes the file.
4) Other than what I just described, don't change the program
in any way. The program asks for a file type (random, binary, or
text) and the name of the file to create. In a loop it inputs a
person's name (string), a person's age (int), and a person's
annual salary (double). It writes to a file of the appropriate
type. The loop terminates when the user indicates that inputting
is complete. The program then asks if another file should be
created. If the answer is yes, the whole process starts again.
This and all of the java driver programs should be saved in your
lab2 folder but not in the cs258 sub-folder.
5) Note: The method signatures for accessing all of the three
types of files (binary, random, and text) are on the class web-
site. Go to power point slides and click on week two. This will
help if you didn't take accurate notes in class.
6) Write a main program to read binary files (BinReader.java).
This program only needs to be able to read and display records
from a Binary file that was created by the writers program.
7) Write a main program to read random files
(RandReader.java). This program only needs to be able to read
and display records from a Binary file that was created by the
writers program. Make sure that this program reads and displays
2. records in reverse order. DO NOT USE AN ARRAY!!!
8) In your Lab2 folder, create a subfolder within lab2 named
cs258. Download Keyboard.java from the class web-site to that
folder. Add a new first line of Keyboard.java with the
statement, package cs258;. This line will make Keyboard.java
part of the cs258 package. The driver program shown below has
an import ‘cs258.*;’ statement to access the java files in this
package.
9) Modify Keyboard.java. We want to extend this class so it
can be extended to allow access to multiple files. The changes
follow:
a. Remove all static references. This is necessary so that there
will be an input stream variable (in) in each object.
b. Change the private modifier of the in and current_token
variables to protected. Change the private modifier to protected
in all of the signature lines of the overloaded getNextToken
methods.
c. Create a constructor that instantiates the input stream for
keyboard input. Remove the instantiation from the original
declaration line for the in variable. The constructor doesn't need
any parameters.
10)Create a class TextRead in the file TextRead.java; store this
file in the cs258 folder. This class should also be part of the
cs258 package so be sure to include the package statement. This
class should extend the Keyboard class, so all of
Keyboard.java’s methods are available. It should contain a
constructor that instantiates a sequential text file stream. It
needs also to include an end of file and a close method. Note
that since it extends the Keyboard class, all of Keyboard's
methods are available. The class API follows:
public class TextRead extends Keyboard
{ public TextRead(String filename) {}
public boolean close() {}
public boolean endOfFile() {}
}
3. Your job is to complete these three methods.
11)I’ve included the source for the program to read text files
(TextReader.java) and display its contents. It uses two files, so
make sure that your modified TextRead program works with it.
Be careful if you cut and paste this program. The string variable
spaces doesn't cut and paste correctly. You will have to correct
it appropriately. Do not make any other changes to this
program.
12)Answer the synthesis questions in an rtf or doc file
(answers.rtf or answers.doc). Type your name and the lab
number on this file and include the questions with the answers.
13)Zip your Eclipse project along with the synthesis answers
and email to [email protected]
// This program reads the SeqText.dat and seqText2.dat files.
// These files were created by TextWriter.
// They are in sequential text format.
// They contain records of name, age, and salary.
import java.io.*;
import java.text.*;
import cs258.*;
public class TextReader
{ public static final int NAME_SIZE=30;
public static void main(String args[])
{ String name;
int age;
double salary;
if (!new File("seqtext.dat").exists() ||
!new File("seqtext2.dat").exists())
4. { System.out.println("Files don't exist");
System.exit(1);
}
TextRead file1 = new TextRead("seqtext.dat");
TextRead file2 = new TextRead("seqtext2.dat");
NumberFormat money =
NumberFormat.getCurrencyInstance();
DecimalFormat fmt = new DecimalFormat("##0.##");
String spaces = " ";
System.out.println("Text file readern");
do
{ if (!file1.endOfFile())
{ name = file1.readString();
age = file1.readInt();
salary = file1.readDouble();
System.out.print(name);
if (name.length() < NAME_SIZE)
System.out.print
( spaces.substring(0, NAME_SIZE-name.length())
);
System.out.println
( " " + fmt.format(age) + " " +
money.format(salary) );
}
if (!file2.endOfFile())
{ name = file2.readString();
age = file2.readInt();
salary = file2.readDouble();
System.out.print(name);
if (name.length() < NAME_SIZE)
System.out.print
( spaces.substring(0, NAME_SIZE-name.length())
);
System.out.println
( " " + fmt.format(age) + " " +
5. money.format(salary) );
}
} while (!file1.endOfFile()||!file2.endOfFile());
file1.close();
file2.close();
System.out.println("nTextReader complete; data printed");
}
}
// This program writes different types of files.
// Random, Binary, and Text.
// Created 3/29/2004 for the lab 2 cs258 project.
import java.io.*;
import java.security.*;
public class Writers
{ private final static int RECORDSIZE = 128;
private final static int NAME_SIZE = 30;
private final static String spaces = " ";
// Keyboard input stream.
private final static BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[])
{
// File related variables variables.
Writer out = null;
String fileType = null, fileName = null;
// Data variables.
String name;
int age, recordNumber = 0;
double salary;
String doMore;
6. boolean quit, moreFiles;
System.out.println("File writer program");
do
{ try
{ do
{ System.out.print("Enter file type (text, binary,
random): ");
fileType = in.readLine().toLowerCase();
} while ( !("text".startsWith(fileType) ||
"binary".startsWith(fileType) ||
"random".startsWith(fileType))
);
System.out.print("Enter the file name: ");
fileName = in.readLine().toLowerCase();
switch (fileType.charAt(0))
{ case 't': out = new Text(fileName);
break;
case 'b': out = new Binary(fileName);
break;
case 'r': recordNumber = 0;
out = new Random( fileName,
RECORDSIZE);
break;
default: throw new InvalidParameterException();
}
do
{
System.out.print("Enter Name: ");
name = in.readLine() + spaces;
name = name.substring(0,NAME_SIZE);
age = getAge();
salary = getSalary();
7. out.write(name, age, salary, recordNumber);
recordNumber++;
System.out.println("n Type 'quit' to exit: ");
doMore = in.readLine().toLowerCase();
quit = (doMore.length()>0 &&
"quit".startsWith(doMore));
} while (!quit);
}
catch (InvalidParameterException e)
{ System.out.println("Unknown case");
System.exit(1);
}
catch (IOException e)
{ System.out.println("I/O Error");
}
catch (Exception e)
{ System.out.println("Illegal Entry");
}
finally { try { out.close(); } catch(Exception e) {} }
System.out.println("Another file? (y/n) ");
try
{ doMore = in.readLine().toLowerCase();
moreFiles = (doMore.length()>0 &&
"yes".startsWith(doMore));
}
catch (Exception e) {moreFiles = false;}
} while (moreFiles);
System.out.println("File write complete; data is in
"+fileName+"n");
} // End void main()
// Method to input an age.
8. private static int getAge()
{ int age = -1;
String inputString = null;
do
{ try
{ System.out.print("Enter Age: ");
inputString = in.readLine();
age = Integer.parseInt(inputString);
if (age<0 || age>100) throw new Exception();
return age;
}
catch (Exception e) {System.out.println("Illegal age, try
again");}
} while (true);
}
// Method to input a salary.
private static double getSalary()
{ double salary = -1;
String inputString = null;
do
{ try
{ System.out.print("Enter Salary: ");
inputString = in.readLine();
salary = Double.parseDouble(inputString);
if (salary<0 || salary>1000000) throw new Exception();
return salary;
}
catch (Exception e) {System.out.println("Illegal salary,
try again");}
} while (true);
}
}
9. abstract class Writer
{ public abstract void write(String name, int age, double salary,
int record)
throws IOException;
public abstract void close();
}
class Random extends Writer
{ RandomAccessFile out;
int recordSize;
public Random(String fileName, int recordSize)
throws FileNotFoundException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
{ }
}
class Binary extends Writer
{ DataOutputStream out = null;
public Binary(String fileName) throws IOException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
10. { }
}
class Text extends Writer
{ PrintWriter out = null;
public Text(String fileName) throws IOException
{ }
public void write(String name, int age, double salary, int
record)
throws IOException
{ }
public void close()
{ }
}
//***************************************************
*****************
// Keyboard.java
//
// Facilitates keyboard input by abstracting details about input
// parsing, conversions, and exception handling.
//***************************************************
*****************
import java.io.*;
import java.util.*;
public class Keyboard
{
//************* Error Handling Section
**************************
11. private static boolean printErrors = true;
private static int errorCount = 0;
//-----------------------------------------------------------------
// Returns the current error count.
//-----------------------------------------------------------------
public static int getErrorCount() {return errorCount;}
//-----------------------------------------------------------------
// Resets the current error count to zero.
//-----------------------------------------------------------------
public static void resetErrorCount (int count) {errorCount =
0;}
//-----------------------------------------------------------------
// Returns a boolean indicating whether input errors are
// currently printed to standard output.
//-----------------------------------------------------------------
public static boolean getPrintErrors() {return printErrors;}
//-----------------------------------------------------------------
// Sets a boolean indicating whether input errors are to be
// printed to standard output.
//-----------------------------------------------------------------
public static void setPrintErrors (boolean flag) {printErrors
= flag;}
//-----------------------------------------------------------------
// Increments the error count and prints the error message if
// appropriate.
//-----------------------------------------------------------------
12. private static void error (String str)
{ errorCount++;
if (printErrors) System.out.println (str);
}
//************* Tokenized Input Stream Section
******************
private static String current_token = null;
private static StringTokenizer reader;
private static BufferedReader in
= new BufferedReader (new
InputStreamReader(System.in));
//-----------------------------------------------------------------
// Gets the next input token assuming it may be on
subsequent
// input lines.
//-----------------------------------------------------------------
private static String getNextToken() {return getNextToken
(true);}
//-----------------------------------------------------------------
// Gets the next input token, which may already have been
read.
//-----------------------------------------------------------------
private static String getNextToken (boolean skip)
{ String token;
if (current_token == null) token = getNextInputToken
(skip);
else
{ token = current_token;
current_token = null;
13. }
return token;
}
//-----------------------------------------------------------------
// Gets the next token from the input, which may come from
the
// current input line or a subsequent one. The parameter
// determines if subsequent lines are used.
//-----------------------------------------------------------------
private static String getNextInputToken (boolean skip)
{ final String delimiters = " tnrf";
String token = null;
try
{ if (reader == null)
reader = new StringTokenizer(in.readLine(), delimiters,
true);
while (token == null || ((delimiters.indexOf (token) >= 0)
&& skip))
{ while (!reader.hasMoreTokens())
reader = new StringTokenizer(in.readLine(),
delimiters,true);
token = reader.nextToken();
}
}
catch (Exception exception) {token = null;}
return token;
}
//-----------------------------------------------------------------
// Returns true if there are no more tokens to read on the
// current input line.
//-----------------------------------------------------------------
14. public static boolean endOfLine() {return
!reader.hasMoreTokens();}
//************* Reading Section
*********************************
//-----------------------------------------------------------------
// Returns a string read from standard input.
//-----------------------------------------------------------------
public static String readString()
{ String str;
try
{ str = getNextToken(false);
while (! endOfLine())
{ str = str + getNextToken(false);
}
}
catch (Exception exception)
{ error ("Error reading String data, null value returned.");
str = null;
}
return str;
}
//-----------------------------------------------------------------
// Returns a space-delimited substring (a word) read from
// standard input.
//-----------------------------------------------------------------
public static String readWord()
{ String token;
try
{ token = getNextToken();
}
catch (Exception exception)
{ error ("Error reading String data, null value returned.");
15. token = null;
}
return token;
}
//-----------------------------------------------------------------
// Returns a boolean read from standard input.
//-----------------------------------------------------------------
public static boolean readBoolean()
{ String token = getNextToken();
boolean bool;
try
{ if (token.toLowerCase().equals("true")) bool = true;
else if (token.toLowerCase().equals("false")) bool = false;
else
{ error ("Error reading boolean data, false value
returned.");
bool = false;
}
}
catch (Exception exception)
{ error ("Error reading boolean data, false value
returned.");
bool = false;
}
return bool;
}
//-----------------------------------------------------------------
// Returns a character read from standard input.
//-----------------------------------------------------------------
public static char readChar()
{ String token = getNextToken(false);
char value;
16. try
{ if (token.length() > 1)
{ current_token = token.substring (1, token.length());
} else current_token = null;
value = token.charAt (0);
}
catch (Exception exception)
{ error ("Error reading char data, MIN_VALUE value
returned.");
value = Character.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns an integer read from standard input.
//-----------------------------------------------------------------
public static int readInt()
{ String token = getNextToken();
int value;
try
{ value = Integer.parseInt (token);
}
catch (Exception exception)
{ error ("Error reading int data, MIN_VALUE value
returned.");
value = Integer.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns a long integer read from standard input.
//-----------------------------------------------------------------
17. public static long readLong()
{ String token = getNextToken();
long value;
try
{ value = Long.parseLong (token);
}
catch (Exception exception)
{ error ("Error reading long data, MIN_VALUE value
returned.");
value = Long.MIN_VALUE;
}
return value;
}
//-----------------------------------------------------------------
// Returns a float read from standard input.
//-----------------------------------------------------------------
public static float readFloat()
{ String token = getNextToken();
float value;
try
{ value = (new Float(token)).floatValue();
}
catch (Exception exception)
{ error ("Error reading float data, NaN value returned.");
value = Float.NaN;
}
return value;
}
//-----------------------------------------------------------------
// Returns a double read from standard input.
//-----------------------------------------------------------------
public static double readDouble()
18. { String token = getNextToken();
double value;
try
{ value = (new Double(token)).doubleValue();
}
catch (Exception exception)
{ error ("Error reading double data, NaN value returned.");
value = Double.NaN;
}
return value;
}
}