SlideShare a Scribd company logo
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 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() {}
}
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())
{ 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) + " " +
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;
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();
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.
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);
}
}
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()
{ }
}
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
**************************
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.
//-----------------------------------------------------------------
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;
}
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.
//-----------------------------------------------------------------
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.");
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;
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.
//-----------------------------------------------------------------
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()
{ 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;
}
}
Ad

More Related Content

Similar to Description 1) Create a Lab2 folder for this project2.docx (20)

M251_Meeting 7 (Exception Handling and Text IO).ppt
M251_Meeting 7 (Exception Handling and Text IO).pptM251_Meeting 7 (Exception Handling and Text IO).ppt
M251_Meeting 7 (Exception Handling and Text IO).ppt
smartashammari
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
Java 3 Computer Science.pptx
Java 3 Computer Science.pptxJava 3 Computer Science.pptx
Java 3 Computer Science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
IO and threads Java
IO and threads JavaIO and threads Java
IO and threads Java
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Lab 1 Essay
Lab 1 EssayLab 1 Essay
Lab 1 Essay
Melissa Moore
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
atulkapoor33
 
15. text files
15. text files15. text files
15. text files
Konstantin Potemichev
 
Files nts
Files ntsFiles nts
Files nts
kalyani66
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
Kulachi Hansraj Model School Ashok Vihar
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
Python files creation read,write Unit 5.pptx
Python files creation read,write Unit 5.pptxPython files creation read,write Unit 5.pptx
Python files creation read,write Unit 5.pptx
shakthi10
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
UNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering studentsUNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
Files that are designed to be read by human beings
Files that are designed to be read by human beingsFiles that are designed to be read by human beings
Files that are designed to be read by human beings
ManishKumar475693
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
Gagan Agrawal
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 
M251_Meeting 7 (Exception Handling and Text IO).ppt
M251_Meeting 7 (Exception Handling and Text IO).pptM251_Meeting 7 (Exception Handling and Text IO).ppt
M251_Meeting 7 (Exception Handling and Text IO).ppt
smartashammari
 
Write a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdfWrite a program in java that asks a user for a file name and prints .pdf
Write a program in java that asks a user for a file name and prints .pdf
atulkapoor33
 
C++ - UNIT_-_V.pptx which contains details about File Concepts
C++  - UNIT_-_V.pptx which contains details about File ConceptsC++  - UNIT_-_V.pptx which contains details about File Concepts
C++ - UNIT_-_V.pptx which contains details about File Concepts
ANUSUYA S
 
Python files creation read,write Unit 5.pptx
Python files creation read,write Unit 5.pptxPython files creation read,write Unit 5.pptx
Python files creation read,write Unit 5.pptx
shakthi10
 
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docximport java.io.BufferedReader;import java.io.BufferedWriter;.docx
import java.io.BufferedReader;import java.io.BufferedWriter;.docx
wilcockiris
 
Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz Java history, versions, types of errors and exception, quiz
Java history, versions, types of errors and exception, quiz
SAurabh PRajapati
 
UNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering studentsUNIT –5.pptxpython for engineering students
UNIT –5.pptxpython for engineering students
SabarigiriVason
 
Files that are designed to be read by human beings
Files that are designed to be read by human beingsFiles that are designed to be read by human beings
Files that are designed to be read by human beings
ManishKumar475693
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
Gagan Agrawal
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to StreamsJava IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
cherryreddygannu
 

More from theodorelove43763 (20)

Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docxExam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
theodorelove43763
 
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docxEvolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
theodorelove43763
 
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docxexam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
theodorelove43763
 
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docxEvolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
theodorelove43763
 
Evidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docxEvidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docx
theodorelove43763
 
Evidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docxEvidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docx
theodorelove43763
 
Evidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxEvidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docx
theodorelove43763
 
Evidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docxEvidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docx
theodorelove43763
 
Evidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docxEvidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docx
theodorelove43763
 
Everyone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docxEveryone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docx
theodorelove43763
 
Even though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docxEven though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docx
theodorelove43763
 
Even though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docxEven though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docx
theodorelove43763
 
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docxEvaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
theodorelove43763
 
Evaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docxEvaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docx
theodorelove43763
 
Evaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docxEvaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docx
theodorelove43763
 
Evaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docxEvaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docx
theodorelove43763
 
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback  Addressi.docxEvaluating 19-Channel Z-score Neurofeedback  Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
theodorelove43763
 
Evaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docxEvaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docx
theodorelove43763
 
Evaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docxEvaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docx
theodorelove43763
 
Evaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docxEvaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docx
theodorelove43763
 
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docxExam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
Exam Questions1. (Mandatory) Assess the strengths and weaknesse.docx
theodorelove43763
 
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docxEvolving Leadership roles in HIM1. Increased adoption of hea.docx
Evolving Leadership roles in HIM1. Increased adoption of hea.docx
theodorelove43763
 
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docxexam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
exam 2 logiWhatsApp Image 2020-01-18 at 1.01.20 AM (1).jpeg.docx
theodorelove43763
 
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docxEvolution of Terrorism300wrdDo you think terrorism has bee.docx
Evolution of Terrorism300wrdDo you think terrorism has bee.docx
theodorelove43763
 
Evidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docxEvidence-based practice is an approach to health care where health c.docx
Evidence-based practice is an approach to health care where health c.docx
theodorelove43763
 
Evidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docxEvidence-Based EvaluationEvidence-based practice is importan.docx
Evidence-Based EvaluationEvidence-based practice is importan.docx
theodorelove43763
 
Evidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docxEvidence TableStudy CitationDesignMethodSampleData C.docx
Evidence TableStudy CitationDesignMethodSampleData C.docx
theodorelove43763
 
Evidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docxEvidence SynthesisCritique the below evidence synthesis ex.docx
Evidence SynthesisCritique the below evidence synthesis ex.docx
theodorelove43763
 
Evidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docxEvidence Collection PolicyScenarioAfter the recent secur.docx
Evidence Collection PolicyScenarioAfter the recent secur.docx
theodorelove43763
 
Everyone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docxEveryone Why would companies have quality programs even though they.docx
Everyone Why would companies have quality programs even though they.docx
theodorelove43763
 
Even though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docxEven though technology has shifted HRM to strategic partner, has thi.docx
Even though technology has shifted HRM to strategic partner, has thi.docx
theodorelove43763
 
Even though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docxEven though people are aware that earthquakes and volcanoes typi.docx
Even though people are aware that earthquakes and volcanoes typi.docx
theodorelove43763
 
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docxEvaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
Evaluative Essay 2 Grading RubricCriteriaLevels of Achievement.docx
theodorelove43763
 
Evaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docxEvaluation Title Research DesignFor this first assignment, .docx
Evaluation Title Research DesignFor this first assignment, .docx
theodorelove43763
 
Evaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docxEvaluation is the set of processes and methods that managers and sta.docx
Evaluation is the set of processes and methods that managers and sta.docx
theodorelove43763
 
Evaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docxEvaluation Plan with Policy RecommendationAfter a program ha.docx
Evaluation Plan with Policy RecommendationAfter a program ha.docx
theodorelove43763
 
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback  Addressi.docxEvaluating 19-Channel Z-score Neurofeedback  Addressi.docx
Evaluating 19-Channel Z-score Neurofeedback Addressi.docx
theodorelove43763
 
Evaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docxEvaluate the history of the Data Encryption Standard (DES) and then .docx
Evaluate the history of the Data Encryption Standard (DES) and then .docx
theodorelove43763
 
Evaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docxEvaluate the Health History and Medical Information for Mrs. J.,.docx
Evaluate the Health History and Medical Information for Mrs. J.,.docx
theodorelove43763
 
Evaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docxEvaluate the environmental factors that contribute to corporate mana.docx
Evaluate the environmental factors that contribute to corporate mana.docx
theodorelove43763
 
Ad

Recently uploaded (20)

Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptxTERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
TERMINOLOGIES,GRIEF PROCESS AND LOSS AMD ITS TYPES .pptx
PoojaSen20
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Module_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptxModule_2_Types_and_Approaches_of_Research (2).pptx
Module_2_Types_and_Approaches_of_Research (2).pptx
drroxannekemp
 
PUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for HealthPUBH1000 Slides - Module 11: Governance for Health
PUBH1000 Slides - Module 11: Governance for Health
JonathanHallett4
 
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
DEATH & ITS TYPES AND PHYSIOLOGICAL CHANGES IN BODY AFTER DEATH, PATIENT WILL...
PoojaSen20
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
libbys peer assesment.docx..............
libbys peer assesment.docx..............libbys peer assesment.docx..............
libbys peer assesment.docx..............
19lburrell
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptxANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
ANTI-VIRAL DRUGS unit 3 Pharmacology 3.pptx
Mayuri Chavan
 
COPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDFCOPA Apprentice exam Questions and answers PDF
COPA Apprentice exam Questions and answers PDF
SONU HEETSON
 
How to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo SlidesHow to Add Button in Chatter in Odoo 18 - Odoo Slides
How to Add Button in Chatter in Odoo 18 - Odoo Slides
Celine George
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
Ad

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; } }
  翻译: