One way is to use the new_master.txt file supplied/created by the last program and a transaction file that looks like this:
to_delete.txt
1001
1002
1010
So 3 records should be deleted from new_master.
import java.io.*;
/**
* Illustrate updating a master file from a transaction file
*/
public class AddEmployees
{
private static final String MASTER = "master.txt";
private static final String TRANS = "transaction.txt";
private static final String NEW_MASTER = "new_master.txt";
private static final String SPLITTER = "@";
// Files to read and write.
private TextFileReader mr; // master
private TextFileReader tr; // transaction
private TextFileWriter mw; // new master
public static void main(String[] args){ new AddEmployees(); }
public AddEmployees()
{
openFiles();
doUpdate();
closeFiles();
}
private void openFiles()
{
mr = new TextFileReader(MASTER);
tr = new TextFileReader(TRANS);
mw = new TextFileWriter(NEW_MASTER);
}
// Assumes neither file is completely empty
private void doUpdate()
{
// While there are more transaction records
String trecord = readRecord(tr);
boolean endMaster = false;
while (!trecord.equals("EOF") && !endMaster )
{
// extract the ID
int tid = Integer.parseInt(trecord.substring(0,4));
// Read records from master until EOF reached
String mrecord = readRecord(mr);
while (!mrecord.equals("EOF"))
{
// extract the id
int mid = Integer.parseInt(mrecord.substring(0,4));
// comapare id's
while (mid > tid)
{
// insert new record, read new transaction record
writeRecord(mw, trecord);
trecord = readRecord(tr);
tid = Integer.parseInt(trecord.substring(0,4));
}
// write current record to the new master
writeRecord(mw, mrecord);
// Read another master record
mrecord = readRecord(mr);
}
endMaster = true;
}
// End of master, could still be more records to write from transaction
while (!trecord.equals("EOF"))
{
writeRecord(mw, trecord);
trecord = readRecord(tr);
}
}
private void closeFiles()
{
// Could do file renaming here if desired
mr.close();
tr.close();
mw.close();
}
// reads four lines from a text file
// represents an employee record
private String readRecord(TextFileReader tf)
{
String result = "EOF";
String line = tf.readLine();
if (line != null){ result = line; } // read the id
line = tf.readLine();
if (line != null){ result = result + SPLITTER + line; } // read the name
line = tf.readLine();
if (line != null){ result = result + SPLITTER + line; } // read the hours worked
line = tf.readLine();
if (line != null){ result = result + SPLITTER + line; } // read the hourly rate
return result;
}
// Assumes 4 bits of text in the String, with @ as the separator
private void writeRecord(TextFileWriter tf, String s)
{
// Unfortunately println to a file strips out
// any "/n" new lines so we have to split the String
// back into its components.
String[] result = s.split(SPLITTER);
tf.println(result[0]);
tf.println(result[1]);
tf.println(result[2]);
tf.println(result[3]);
}
}

New Topic/Question
Reply



MultiQuote





|