4. FileMatch类
// Fig. 15.6: ReadTextFile.java
// This program reads a text file and displays each record.
package ch15.exercises;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.IllegalStateException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class FileMatch
{
private static Scanner inOldMaster;
private static Scanner inTransaction;
private static Formatter outNewMaster;
private static Formatter logfile;
public static void main(String[] args) throws FileNotFoundException
{
openOldMaster();
openTransaction();
openNewMaster();
openLogFile();
readOldMasterRecords();
readTransactionRecords();
match();
closeFile();
}
// open file clients.txt
public static void openOldMaster()
{
try
{
inOldMaster = new Scanner(Paths.get("oldmast.txt"));
}
catch (IOException ioException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public static void openTransaction()
{
try
{
inTransaction = new Scanner(Paths.get("trans.txt"));
}
catch (IOException ioException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public static void openNewMaster()
{
try
{
outNewMaster = new Formatter("newmast.txt");// open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
public static void openLogFile()
{
try
{
logfile = new Formatter("log.txt");// open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
// read record from file
public static void readOldMasterRecords()
{
System.out.printf("%-10s%-12s%-12s%10s%n", "Account",
"First Name", "Last Name", "Balance");
try
{
while (inOldMaster.hasNext()) // while there is more to read
{
// display record contents
System.out.printf("%-10d%-12s%-12s%10.2f%n", inOldMaster.nextInt(),
inOldMaster.next(), inOldMaster.next(), inOldMaster.nextDouble());
}
}
catch (NoSuchElementException elementException)
{
System.err.println("File improperly formed. Terminating.");
}
catch (IllegalStateException stateException)
{
System.err.println("Error reading from file. Terminating.");
}
} // end method readRecords
// read record from file
public static void readTransactionRecords()
{
System.out.printf("%-10s%10s%n", "Account",
"Amount");
try
{
while (inTransaction.hasNext()) // while there is more to read
{
// display record contents
System.out.printf("%-10d%10.2f%n", inTransaction.nextInt(),
inTransaction.nextDouble());
}
}
catch (NoSuchElementException elementException)
{
System.err.println("File improperly formed. Terminating.");
}
catch (IllegalStateException stateException)
{
System.err.println("Error reading from file. Terminating.");
}
} // end method readRecords
public static void match() throws FileNotFoundException
{
Account account = new Account();
TransactionRecord transaction = new TransactionRecord();
Log log = new Log();
int n=1;
int mn=1;
boolean matched =false;
boolean reopened =false;
//reset trans and oldmast to generate new master file
openTransaction();
openOldMaster();
//new master file generation
try
{
System.out.println("inOldMaster started");
while (inOldMaster.hasNext()) // loop until end-of-file indicator
{
System.out.println("old master iteration started-"+(n));
account.setAccount(inOldMaster.nextInt());
account.setFirstName(inOldMaster.next());
account.setLastName(inOldMaster.next());
account.setBalance(inOldMaster.nextDouble());
System.out.println("old master iteration completed-"+(n++));
System.out.println("MasterAccount:"+account.getAccount());
//System.out.println("MasterBalance:"+account.getBalance());
{
try
{
while (inTransaction.hasNext()) // while there is more to read
{
transaction.setAccount(inTransaction.nextInt());
transaction.setAmount(inTransaction.nextDouble());
System.out.println("TransactionAccount:"+transaction.getAccount());
/*When a match occurs (i.e., records with the same account number appear
* in both the master file and the transaction file), add the dollar amount
* in the transaction record to the current balance in the master record,
* and write the "newmast.txt" record. (Assume that purchases are indicated
* by positive amounts in the transaction file and payments by negative amounts.)*/
if (account.getAccount()==transaction.getAccount()){
System.out.println("Account matched-"+(mn++));
System.out.println("if:MasterAccount:"+account.getAccount());
System.out.println("if:TransactionAccount:"+transaction.getAccount());
account.combine(transaction);
outNewMaster.format("%d %s %s %.2f%n",
account.getAccount(), account.getFirstName(),
account.getLastName(), account.getBalance());
matched = true;
break;
}
matched =false;
}
/*When there’s a master record for a particular account, but no corresponding transaction record,
merely write the master record to "newmast.txt".*/
if (!matched)
{
outNewMaster.format("%d %s %s %.2f%n",
account.getAccount(), account.getFirstName(),
account.getLastName(), account.getBalance());
}
openTransaction();
}
catch (NoSuchElementException elementException)
{
System.err.println("File improperly formed. Terminating.");
}
catch (IllegalStateException stateException)
{
System.err.println("Error reading from file. Terminating.");
}
}
}
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
}
//reset trans and oldmast to generate log file
openTransaction();
openOldMaster();
//log file generation
try
{
while (inTransaction.hasNext()) // while there is more to read
{
transaction.setAccount(inTransaction.nextInt());
transaction.setAmount(inTransaction.nextDouble());
try
{
while (inOldMaster.hasNext()) // loop until end-of-file indicator
{
account.setAccount(inOldMaster.nextInt());
account.setFirstName(inOldMaster.next());
account.setLastName(inOldMaster.next());
account.setBalance(inOldMaster.nextDouble());
if (account.getAccount()==transaction.getAccount()){
matched = true;
break;
}
matched = false;
}
/*When there’s a transaction record,
but no corresponding master record, print to a log file the message "Unmatched
transaction record for account number…" (fill in the account number from the transaction
record). The log file should be a text file named "log.txt".*/
if (!matched)
logfile.format("Unmatched transaction record for account number:%d%n", transaction.getAccount());
openOldMaster();
}
catch (NoSuchElementException elementException)
{
System.err.println("File improperly formed. Terminating.");
}
catch (IllegalStateException stateException)
{
System.err.println("Error reading from file. Terminating.");
}
}
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
}
}
// close file and terminate application
public static void closeFile()
{
if (inOldMaster != null)
{
inOldMaster.close();
System.out.println("inOldMaster closed");}
if (inTransaction != null){
inTransaction.close();
System.out.println("inTransaction closed");}
if (outNewMaster != null){
outNewMaster.close();
System.out.println("outNewMaster closed");}
if (logfile != null){
logfile.close();
System.out.println("logfile closed");}
}
} // end class ReadTextFile
5. CreateMasterFiles类(可选)
// Fig. 15.3: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
package ch15.exercises;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateMasterFiles
{
private static Formatter oldmast; // outputs text to a file
public static void main(String[] args)
{
openFile();
addMasterRecords();
closeFile();
}
// open file trans.txt and oldmast.txt
public static void openFile()
{
try
{
oldmast = new Formatter("oldmast.txt"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
public static void addMasterRecords()
{
/* Scanner inOldMaster = new Scanner(Paths.get("oldmast.txt"));
Scanner inTransaction = new Scanner(Paths.get("trans.txt"));*/
Scanner inOldMaster = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (inOldMaster.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
oldmast.format("%d %s %s %.2f%n", inOldMaster.nextInt(),
inOldMaster.next(), inOldMaster.next(), inOldMaster.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
inOldMaster.nextLine(); // discard input so user can try again
}
System.out.print("? ");
}
}
// close file
public static void closeFile()
{
if (oldmast != null)
oldmast.close();
}
} // end class CreateTextFile
6. CreateTransactionFiles类 (可选)
// Fig. 15.3: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
package ch15.exercises;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTransactionFiles
{
private static Formatter trans;
public static void main(String[] args)
{
openFile();
addTransactionRecords();
closeFile();
}
// open file trans.txt and oldmast.txt
public static void openFile()
{
try
{
trans = new Formatter("trans.txt"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
public static void addTransactionRecords()
{
Scanner inTransaction = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, transaction amount",
"Enter end-of-file indicator to end input.");
while (inTransaction.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
trans.format("%d %.2f%n", inTransaction.nextInt(),
inTransaction.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
inTransaction.nextLine(); // discard input so user can try again
}
System.out.print("? ");
}
}
// close file
public static void closeFile()
{
if (trans != null)
trans.close();
}
} // end class CreateTextFile
测试用例及测试结果:
测试用例1
oldmast
100 pd huang 100
200 sc jiang 158
300 sn huang 168
800 hb huang 2
Trans
100 30
200 158
800 998
900 998
1000 666
300 888
newmast (Expected) logfile(Expected)
100 pd huang 130 900
200 sc jiang 316 1000
300 sn huang 1056
800 hb huang 1000
newmast (Actual) logfile(Actual)
100 pd huang 130 900
200 sc jiang 316 1000
300 sn huang 1056
800 hb huang 1000
Test Result:
Pass
测试用例1
oldmast
100 pd huang 100
200 sc jiang 158
300 sn huang 168
800 hb huang 2
Trans
100 30
200 158
800 998
900 998
1000 666
300 888
newmast (Expected) logfile(Expected)
100 pd huang 130 900
200 sc jiang 316 1000
300 sn huang 1056
800 hb huang 1000
newmast (Actual) logfile(Actual)
100 pd huang 130 900
200 sc jiang 316 1000
300 sn huang 1056
800 hb huang 1000
Test Result:
Pass
测试用例2
oldmast
100 pd huang 100
500 sc jiang 158
300 sn huang 168
600 hb huang 2
Trans
100 30
200 158
800 998
900 998
1000 666
300 888
newmast (Expected) logfile(Expected)
100 pd huang 130 200
300 sn huang 1056 800
500 sc jiang 158 900
600 hb huang 2 1000
newmast (Actual) logfile(Actual)
100 pd huang 130 200
500 sc jiang 158 800
300 sn huang 1056 900
600 hb huang 2 1000
Test Result:
Pass
不错,再一次实现了个人在技术上的突破(文件的读写操作及合并算法),不忘初心,方得始终!加油!
100 pd huang 100
500 sc jiang 158
300 sn huang 168
600 hb huang 2
Trans
100 30
200 158
800 998
900 998
1000 666
300 888
newmast (Expected) logfile(Expected)
100 pd huang 130 200
300 sn huang 1056 800
500 sc jiang 158 900
600 hb huang 2 1000
newmast (Actual) logfile(Actual)
100 pd huang 130 200
500 sc jiang 158 800
300 sn huang 1056 900
600 hb huang 2 1000
Test Result:
Pass
不错,再一次实现了个人在技术上的突破(文件的读写操作及合并算法),不忘初心,方得始终!加油!