📄 binaryfilereadwrite.java
字号:
package sequentialProcessing;
import java.io.*;
import java.util.StringTokenizer;
import dslib.file.ObjectFileUos;
/** Read the data for a sequence of employees from a text file,
write it into a binary file, and then read the binary file
to calculate and print the average hourly wage. */
public class BinaryFileReadWrite
{
/** Create and process a master file. <br>
Analysis: Time = O(n) file reads and writes, n = the number of employees */
public BinaryFileReadWrite() throws Exception
{
createMasterFile();
processMasterFile();
}
/** Read data from a text file to create a master binary file. <br>
Analysis: Time = O(n) file reads and writes, n = the number of employees */
public void createMasterFile() throws Exception
{
BufferedReader inFile = new BufferedReader(new FileReader("employeeList.dat"));
ObjectFileUos masterFile = new ObjectFileUos("masterFile", "rw");
masterFile.wipeOut();
String empName = inFile.readLine();
while (empName != null)
{
StringTokenizer tokenFinder = new StringTokenizer (inFile.readLine());
int empNumber = Integer.parseInt(tokenFinder.nextToken());
float empRate = Float.parseFloat(tokenFinder.nextToken());
String empClass = tokenFinder.nextToken();
Employee emp = new Employee(empName, empNumber, empRate, empClass);
masterFile.writeObject(emp);
empName = inFile.readLine();
}
inFile.close();
masterFile.close();
}
/** Read employees from a binary file, and compute and print the average hourly rate. <br>
Analysis: Time = O(n) file reads, n = the number of employees */
public void processMasterFile() throws Exception
{
ObjectFileUos masterFile = new ObjectFileUos("masterFile", "r");
int count = 0;
float total = 0;
while (!masterFile.eof())
{
Employee emp = (Employee) masterFile.readObject();
System.out.println(emp);
count++;
total += emp.rate;
}
System.out.println("The average hourly rate is " + total/count);
masterFile.close();
}
public static void main(String[] args) throws Exception
{
BinaryFileReadWrite ts = new BinaryFileReadWrite();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -