Java ZipFIle Random access
Hi All,
I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
Thanks
I beg your pardon, I did not catch the idea. Why use a ZipFile to access ascii (i.e. text??) file?
Similar Messages
-
Hi All,
I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
ThanksI don't believe that is going to be possible, as the RandomAccessFile class is designed to work only with a file.
You could extract the data from the zip file, write it to a new flat file, and then use RAF on that. -
Modify Record Number in a Random Access File
Hi Does anyone know if I can modify the record number in the random access file hardware.dat for each hardware record each time and update it in hardware.dat to display it? Also why does it say "Record does not exist" if I modify the record number for a hardware and try to update it but could not find that record?
Here is the code below:
// Exercise 14.11: HardwareRecord.java
package org.egan; // packaged for reuse
public class HardwareRecord
private int recordNumber;
private String toolName;
private int quantity;
private double cost;
// no-argument constructor calls other constructor with default values
public HardwareRecord()
this(0,"",0,0.0); // call four-argument constructor
} // end no-argument HardwareRecord constructor
// initialize a record
public HardwareRecord(int number, String tool, int amount, double price)
setRecordNumber(number);
setToolName(tool);
setQuantity(amount);
setCost(price);
} // end four-argument HardwareRecord constructor
// set record number
public void setRecordNumber(int number)
recordNumber = number;
} // end method setRecordNumber
// get record number
public int getRecordNumber()
return recordNumber;
} // end method getRecordNumber
// set tool name
public void setToolName(String tool)
toolName = tool;
} // end method setToolName
// get tool name
public String getToolName()
return toolName;
} // end method getToolName
// set quantity
public void setQuantity(int amount)
quantity = amount;
} // end method setQuantity
// get quantity
public int getQuantity()
return quantity;
} // end method getQuantity
// set cost
public void setCost(double price)
cost = price;
} // end method setCost
// get cost
public double getCost()
return cost;
} // end method getCost
} // end class HardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: RandomAccessHardwareRecord.java
// Subclass of HardwareRecord for random-access file programs.
package org.egan; // package for reuse
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessHardwareRecord extends HardwareRecord
public static final int SIZE = 46;
// no-argument constructor calls other constructor with default values
public RandomAccessHardwareRecord()
this(0,"",0,0.0);
} // end no-argument RandomAccessHardwareRecord constructor
// initialize a RandomAccessHardwareRecord
public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
super(number,tool,amount,price);
} // end four-argument RandomAccessHardwareRecord constructor
// read a record from a specified RandomAccessFile
public void read(RandomAccessFile file) throws IOException
setRecordNumber(file.readInt());
setToolName(readName(file));
setQuantity(file.readInt());
setCost(file.readDouble());
} // end method read
// ensure that name is proper length
private String readName(RandomAccessFile file) throws IOException
char name[] = new char[15], temp;
for(int count = 0; count < name.length; count++)
temp = file.readChar();
name[count] = temp;
} // end for
return new String(name).replace('\0',' ');
} // end method readName
// write a record to specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
file.writeInt(getRecordNumber());
writeName(file, getToolName());
file.writeInt(getQuantity());
file.writeDouble(getCost());
} // end method write
// write a name to file; maximum of 15 characters
private void writeName(RandomAccessFile file, String name) throws IOException
StringBuffer buffer = null;
if (name != null)
buffer = new StringBuffer(name);
else
buffer = new StringBuffer(15);
buffer.setLength(15);
file.writeChars(buffer.toString());
} // end method writeName
} // end RandomAccessHardwareRecord-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFile.java
// creates random-access file by writing 100 empty records to disk.
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class CreateRandomFile
private static final int NUMBER_RECORDS = 100;
// enable user to select file to open
public void createFile()
RandomAccessFile file = null;
try // open file for reading and writing
file = new RandomAccessFile("hardware.dat","rw");
RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
// write 100 blank records
for (int count = 0; count < NUMBER_RECORDS; count++)
blankRecord.write(file);
// display message that file was created
System.out.println("Created file hardware.dat.");
System.exit(0); // terminate program
} // end try
catch (IOException ioException)
System.err.println("Error processing file.");
System.exit(1);
} // end catch
finally
try
if (file != null)
file.close(); // close file
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end finally
} // end method createFile
} // end class CreateRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFileTest.java
// Testing class CreateRandomFile
public class CreateRandomFileTest
// main method begins program execution
public static void main( String args[] )
CreateRandomFile application = new CreateRandomFile();
application.createFile();
} // end main
} // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: MenuOption.java
// Defines an enum type for the hardware credit inquiry program's options.
public enum MenuOption
// declare contents of enum type
PRINT(1),
UPDATE(2),
NEW(3),
DELETE(4),
END(5);
private final int value; // current menu option
MenuOption(int valueOption)
value = valueOption;
} // end MenuOptions enum constructor
public int getValue()
return value;
} // end method getValue
} // end enum MenuOption-------------------------------------------------------------------------------------------------
// Exercise 14.11: FileEditor.java
// This class declares methods that manipulate hardware account records
// in a random access file.
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class FileEditor
RandomAccessFile file; // reference to the file
Scanner input = new Scanner(System.in);
// open the file
public FileEditor(String fileName) throws IOException
file = new RandomAccessFile(fileName, "rw");
} // end FileEditor constructor
// close the file
public void closeFile() throws IOException
if (file != null)
file.close();
} // end method closeFile
// get a record from the file
public RandomAccessHardwareRecord getRecord(int recordNumber)
throws IllegalArgumentException, NumberFormatException, IOException
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
if (recordNumber < 1 || recordNumber > 100)
throw new IllegalArgumentException("Out of range");
// seek appropriate record in a file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.read(file);
return record;
} // end method getRecord
// update record tool name in file
public void updateRecordToolName(int recordNumber, String newToolName)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setToolName(newToolName);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordToolName
// update record in file
public void updateRecordQuantity(int recordNumber, int newQuantity)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setQuantity(newQuantity);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordQuantity
// update record in file
public void updateRecordCost(int recordNumber, double newCost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Record does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record.setCost(newCost);
record = new RandomAccessHardwareRecord(
record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
record.write(file); // write updated record to file
} // end method updateRecordCost
// add record to file
public void newRecord(int recordNumber, String toolName, int quantity, double cost)
throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() != 0)
throw new IllegalArgumentException("Record already exists");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
record = new RandomAccessHardwareRecord(recordNumber, toolName, quantity, cost);
record.write(file); // write record to file
} // end method newRecord
// delete record from file
public void deleteRecord(int recordNumber) throws IllegalArgumentException, IOException
RandomAccessHardwareRecord record = getRecord(recordNumber);
if (record.getRecordNumber() == 0)
throw new IllegalArgumentException("Account does not exist");
// seek appropriate record in file
file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
// create a blank record to write to the file
record = new RandomAccessHardwareRecord();
record.write(file);
} // end method deleteRecord
// read and display records
public void readRecords()
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
try // read a record and display
file.seek(0);
while (true)
do
record.read(file);
while (record.getRecordNumber() == 0);
// display record contents
System.out.printf("%-10d%-15s%-15d%10.2f\n",record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end while
} // end try
catch (EOFException eofException) // close file
return; // end of file was reached
} // end catch
catch (IOException ioException)
System.err.println("Error reading file.");
System.exit(1);
} // end catch
} // end method readRecords
} // end class FileEditor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessor.java
// A transaction processing program using random-access files.
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class TransactionProcessor
private FileEditor dataFile;
private RandomAccessHardwareRecord record;
private MenuOption choices[] = {MenuOption.PRINT, MenuOption.UPDATE, MenuOption.NEW,
MenuOption.DELETE, MenuOption.END};
private Scanner input = new Scanner(System.in);
// get the file name and open the file
private boolean openFile()
try // attempt to open file
// call the helper method to open the file
dataFile = new FileEditor("hardware.dat");
} // end try
catch (IOException ioException)
System.err.println("Error opening file.");
return false;
} // end catch
return true;
} // end method openFile
// close file and terminate application
private void closeFile()
try // close file
dataFile.closeFile();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
// create, update or delete the record
private void performAction(MenuOption action)
int recordNumber = 0; // record number of record
String toolName; // tool name of the hardware instrument
int quantity; // total amount of items
double cost; // hareware tool price
int choice; // choose an update option
int newRecordNumber; // the updated record number
String newToolName; // the updated tool name
int newQuantity; // the updated quantity
double newCost; // the updated cost
try // attempt to manipulate files based on option selected
switch(action) // switch based on option selected
case PRINT:
System.out.println();
dataFile.readRecords();
break;
case NEW:
System.out.printf("\n%s%s\n%s\n%s","Enter record number,",
"tool name, quantity, and cost.","(Record number must be 1 - 100)","? ");
recordNumber = input.nextInt(); // read record number
toolName = input.next(); // read tool name
quantity = input.nextInt(); // read quantity
cost = input.nextDouble(); // read cost
dataFile.newRecord(recordNumber, toolName, quantity, cost); // create new record
break;
case UPDATE:
System.out.print("\nEnter record number to update (1 - 100): ");
recordNumber = input.nextInt();
record = dataFile.getRecord(recordNumber);
if (record.getRecordNumber() == 0)
System.out.println("Record does not exist.");
else
// display record contents
System.out.printf("%-10d%-12s%-12d%10.2f\n\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
System.out.printf("%s%s","\nEnter 1 to update tool name, ",
"2 to update quantity, or 3 to update cost : ");
choice = input.nextInt();
if (choice == 1)
System.out.print("Enter new record tool name : ");
newToolName = input.next();
dataFile.updateRecordToolName(recordNumber,newToolName); // update record
// tool name
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 2)
System.out.print("Enter new record quantity : ");
newQuantity = input.nextInt();
dataFile.updateRecordQuantity(recordNumber,newQuantity); // update record
// quantity
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
else if (choice == 3)
System.out.print("Enter new record cost : ");
newCost = input.nextDouble();
dataFile.updateRecordCost(recordNumber,newCost); // update record cost
// retrieve updated record
record = dataFile.getRecord(recordNumber);
// display updated record
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end else
break;
case DELETE:
System.out.print("\nEnter an account to delete ( 1 - 100): ");
recordNumber = input.nextInt();
dataFile.deleteRecord(recordNumber); // delete record
break;
default:
System.out.println("Invalid action.");
break;
} // end switch
} // end try
catch (NumberFormatException format)
System.err.println("Bad input.");
} // end catch
catch (IllegalArgumentException badRecord)
System.err.println(badRecord.getMessage());
} // end catch
catch (IOException ioException)
System.err.println("Error writing to the file.");
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input.nextLine();
} // end catch
} // end method performAction
// enable user to input menu choice
private MenuOption enterChoice()
int menuChoice = 1;
// display available options
System.out.printf("\n%s\n%s\n%s\n%s\n%s\n%s","Enter your choice",
"1 - List hardware records", "2 - Update a hardware record",
"3 - Add a new hardware record", "4 - Delete a hardware record", "5 - End program\n?");
try
menuChoice = input.nextInt();
catch (NoSuchElementException elementException)
System.err.println("Invalid input.");
System.exit(1);
} // end catch
return choices[menuChoice - 1]; // return choice from user
} // end enterChoice
public void processRequests()
openFile();
// get user's request
MenuOption choice = enterChoice();
while (choice != MenuOption.END)
performAction(choice);
choice = enterChoice();
} // end while
closeFile();
} // end method processRequests
} // end class TransactionProcessor-------------------------------------------------------------------------------------------------
// Exercise 14.11: TransactionProcessorTest.java
// Testing the transaction processor.
public class TransactionProcessorTest
public static void main(String args[])
TransactionProcessor application = new TransactionProcessor();
application.processRequests();
} // end main
} // end class TransactionProcessorTest-------------------------------------------------------------------------------------------------
Below is the sample data to be entered into the random input file hardware.dat :
Record Tool Quantity Cost
Number Name
3 Sander 18 35.99
19 Hammer 128 10.00
26 Jigsaw 16 14.25
39 Mower 10 79.50
56 Saw 8 89.99
76 Screwdriver 236 4.99
81 Sledgehammer 32 19.75
88 Wrench 65 6.48Message was edited by:
egan128
Message was edited by:
egan128
Message was edited by:
egan128Hi Does anyone know if I can modify the record number
in the random access file hardware.dat for each
hardware record each time and update it in
hardware.dat to display it?If the "record number" is data that is stored in the file, then you can modify it. More precisely: it is possible to modify it.
The rest of the question had too many incompatible verbs for me to understand it.
Also why does it say
"Record does not exist" if I modify the record number
for a hardware and try to update it but could not
find that record?"Record does not exist" is a fairly reasonable error message for the situation where a program looks for a record but cannot find it. Are you asking why that particular lump of code actually does that?
(One thousand lines of code removed) -
Random Access File not working, Need Help!!!!
I am having trouble creating and displaying a Random Access File for hardware tools. I have included the code below in eight files:
// Exercise 14.11: HardwareRecord.java
package org.egan; // packaged for reuse
public class HardwareRecord
private int recordNumber;
private String toolName;
private int quantity;
private double cost;
// no-argument constructor calls other constructor with default values
public HardwareRecord()
this(0,"",0,0.0); // call four-argument constructor
} // end no-argument HardwareRecord constructor
// initialize a record
public HardwareRecord(int number, String tool, int amount, double price)
setRecordNumber(number);
setToolName(tool);
setQuantity(amount);
setCost(price);
} // end four-argument HardwareRecord constructor
// set record number
public void setRecordNumber(int number)
recordNumber = number;
} // end method setRecordNumber
// get record number
public int getRecordNumber()
return recordNumber;
} // end method getRecordNumber
// set tool name
public void setToolName(String tool)
toolName = tool;
} // end method setToolName
// get tool name
public String getToolName()
return toolName;
} // end method getToolName
// set quantity
public void setQuantity(int amount)
quantity = amount;
} // end method setQuantity
// get quantity
public int getQuantity()
return quantity;
} // end method getQuantity
// set cost
public void setCost(double price)
cost = price;
} // end method setCost
// get cost
public double getCost()
return cost;
} // end method getCost
} // end class HardwareRecord------------------------------------------------------------------------------------------------
// Exercise 14.11: RandomAccessHardwareRecord.java
// Subclass of HardwareRecord for random-access file programs.
package org.egan; // package for reuse
import java.io.RandomAccessFile;
import java.io.IOException;
public class RandomAccessHardwareRecord extends HardwareRecord
public static final int SIZE = 72;
// no-argument constructor calls other constructor with default values
public RandomAccessHardwareRecord()
this(0,"",0,0.0);
} // end no-argument RandomAccessHardwareRecord constructor
// initialize a RandomAccessHardwareRecord
public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
super(number,tool,amount,price);
} // end four-argument RandomAccessHardwareRecord constructor
// read a record from a specified RandomAccessFile
public void read(RandomAccessFile file) throws IOException
setRecordNumber(file.readInt());
setToolName(readName(file));
setQuantity(file.readInt());
setCost(file.readDouble());
} // end method read
// ensure that name is proper length
private String readName(RandomAccessFile file) throws IOException
char name[] = new char[15], temp;
for(int count = 0; count < name.length; count++)
temp = file.readChar();
name[count] = temp;
} // end for
return new String(name).replace('\0',' ');
} // end method readName
// write a record to specified RandomAccessFile
public void write(RandomAccessFile file) throws IOException
file.writeInt(getRecordNumber());
writeName(file, getToolName());
file.writeInt(getQuantity());
file.writeDouble(getCost());
} // end method write
// write a name to file; maximum of 15 characters
private void writeName(RandomAccessFile file, String name) throws IOException
StringBuffer buffer = null;
if (name != null)
buffer = new StringBuffer(name);
else
buffer = new StringBuffer(15);
buffer.setLength(15);
file.writeChars(buffer.toString());
} // end method writeName
} // end RandomAccessHardwareRecord------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFile.java
// creates random-access file by writing 100 empty records to disk.
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class CreateRandomFile
private static final int NUMBER_RECORDS = 100;
// enable user to select file to open
public void createFile()
RandomAccessFile file = null;
try // open file for reading and writing
file = new RandomAccessFile("hardware.dat","rw");
RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
// write 100 blank records
for (int count = 0; count < NUMBER_RECORDS; count++)
blankRecord.write(file);
// display message that file was created
System.out.println("Created file hardware.dat.");
System.exit(0); // terminate program
} // end try
catch (IOException ioException)
System.err.println("Error processing file.");
System.exit(1);
} // end catch
finally
try
if (file != null)
file.close(); // close file
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end finally
} // end method createFile
} // end class CreateRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: CreateRandomFileTest.java
// Testing class CreateRandomFile
public class CreateRandomFileTest
// main method begins program execution
public static void main( String args[] )
CreateRandomFile application = new CreateRandomFile();
application.createFile();
} // end main
} // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: WriteRandomFile.java
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.NoSuchElementException;
import java.util.Scanner;
import org.egan.RandomAccessHardwareRecord;
public class WriteRandomFile
private RandomAccessFile output;
private static final int NUMBER_RECORDS = 100;
// enable user to choose file to open
public void openFile()
try // open file
output = new RandomAccessFile("hardware.dat","rw");
} // end try
catch (IOException ioException)
System.err.println("File does not exist.");
} // end catch
} // end method openFile
// close file and terminate application
public void closeFile()
try // close file and exit
if (output != null)
output.close();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end method closeFile
// add records to file
public void addRecords()
// object to be written to file
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
int recordNumber = 0;
String toolName;
int quantity;
double cost;
Scanner input = new Scanner(System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator ",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter");
System.out.printf("%s %s\n%s", "Enter record number (1-100),",
"tool name, quantity and cost.","? ");
while (input.hasNext())
try // output values to file
recordNumber = input.nextInt(); // read record number
toolName = input.next(); // read tool name
quantity = input.nextInt(); // read quantity
cost = input.nextDouble(); // read cost
if (recordNumber > 0 && recordNumber <= NUMBER_RECORDS)
record.setRecordNumber(recordNumber);
record.setToolName(toolName);
record.setQuantity(quantity);
record.setCost(cost);
output.seek((recordNumber - 1) * // position to proper
RandomAccessHardwareRecord.SIZE); // location for file
record.write(output);
} // end if
else
System.out.println("Account must be between 0 and 100.");
} // end try
catch (IOException ioException)
System.err.println("Error writing to file.");
return;
} // end catch
catch (NoSuchElementException elementException)
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so enter can try again
} // end catch
System.out.printf("%s %s\n%s","Enter record number (1-100),",
"tool name, quantity and cost.", "? ");
} // end while
} // end method addRecords
} // end class WriteRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: WriteRandomFileTest.java
// Testing class WriteRandomFile
public class WriteRandomFileTest
// main method begins program execution
public static void main( String args[] )
WriteRandomFile application = new WriteRandomFile();
application.openFile();
application.addRecords();
application.closeFile();
} // end main
} // end class WriteRandomFileTest-------------------------------------------------------------------------------------------------
// Exercise 14.11: ReadRandomFile.java
import java.io.EOFException;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.egan.RandomAccessHardwareRecord;
public class ReadRandomFile
private RandomAccessFile input;
// enable user to select file to open
public void openFile()
try // open file
input = new RandomAccessFile("hardware.dat","r");
} // end try
catch (IOException ioException)
System.err.println("File does not exist.");
} // end catch
} // end method openFile
// read and display records
public void readRecords()
RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
try // read a record and display
while(true)
do
record.read(input);
}while (record.getRecordNumber() == 0);
// display record contents
System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
record.getToolName(), record.getQuantity(), record.getCost());
} // end while
} // end try
catch (EOFException eofException)
return; // end of file was reached
} // end catch
catch (IOException ioException)
System.err.println("Error reading file.");
System.exit(1);
} // end catch
} // end method readRecords
// close file and terminate application
public void closeFile()
try // close file and exit
if (input != null)
input.close();
} // end try
catch (IOException ioException)
System.err.println("Error closing file.");
System.exit(1);
} // end catch
} // end methode closeFile
} // end class ReadRandomFile-------------------------------------------------------------------------------------------------
// Exercise 14.11: ReadRandomFileTest.java
// Testing class ReadRandomFile
public class ReadRandomFileTest
// main method begins program execution
public static void main( String args[] )
ReadRandomFile application = new ReadRandomFile();
application.openFile();
application.readRecords();
application.closeFile();
} // end main
} // end class ReadRandomFileTest-------------------------------------------------------------------------------------------------
Below is the sample data to be inputted in the random file:
Record Tool Name Quantity Cost
Number
3 Sander 18 35.99
19 Hammer 128 10.00
26 Jigsaw 16 14.25
39 Mower 10 79.50
56 Saw 8 89.99
76 Screwdriver 236 4.99
81 Sledgehammer 32 19.75
88 Wrench 65 6.48I have managed to fix your program.
The solution
The records are sized by the various Writes that occur.
A record is an int + 15 chars + int + double.
WriteInt writes 4 bytes
WriteChar (Called by WriteChars) write 2 bytes
WriteDouble writes 8 bytes.
(In Java 1.5 )
4 bytes + 30 Bytes + 4Bytes + 8 Bytes. = 46 Bytes.
The details are in the API for Random Acces Files at
http://java.sun.com/j2se/1.5.0/docs/api/java/io/RandomAccessFile.html
The code for RandomAccessHardwareRecord line
public statis final int SIZE = 72needs to have the 72 changed to 46
This should make your code work.
I have hacked around with some other bits and will send you my code if you want but that is the key. The asnwers you were getting illustrated a bunch of bytes being read as (say) an int and beacuse of the wrong record length, they were just a bunch of 4 bytes that evaluated to whetever was at that point in the file.
When the record was written the line
output.seek((recordNumber -1 ) * RandomAccessHardwareRecord.SIZE);had SIZE as 72 and so the seek operation stuck the file pointer in the wrong place.
This kind of stuff is good fun and good learning for mentally getting a feel for record filing but in real problems you either serialize your objects or use XML (better) or use jdbc (possibley even better depending on what you are doing).
I would echo sabre comment about the program being poor though because
If the program is meant to teach, it is littered with overly complex statements and if it is meant to be a meaningful program, the objects are too tied to hardware and DAO is the way to go. The problem that the program has indicates that maybe it is maybe fairly old and not written with java 2 in mind.
As for toString() and "Yuk"
Every class inherits toString() from Object. so if you System.out.println(Any object) then you will get something printed. What gets printed is determined by a complex hieracrchy of classes unless you overRide it with your own method.
If you use UnitTesting (which would prevent incorrect code getting as far as this code did in having an error), then toString() methods are really very useful.
Furthermore, IMO Since RandomAccessHardwareRecord knows how to file itself then I hardly think that knowing how to print itself to the console is a capital offence.
In order to expand on the 72 / 46 byte problem.
Message was edited by:
nerak99 -
Hi All,
I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
ThanksI want to implement this reading process using the RandomAccessFile and read the data randomly.You cannot do this directly on zipped data.
You could simulate random access by skipping over parts of the stream.
Or you could extract the data. -
Manipulating random access dat files
I have a bit of a problem, i inherited a system written in qbasic and i need to be able to manipulate some .dat files which are stored as random access binary files.
my input stream is as follows
RandomAccessFile vansfile = new RandomAccessFile("c:\\vansfile.dat", "rw");
no problems here. i then create a byte array of size record length which happens to be 2462 bytes long and read the first 2462 bytes to the array.
byte[] sss = new byte[2462];
int j j = vansfile.read(sss)
now i know roughly at which offsets some data fields are kept, for instance bytes
sss[0] and sss[1] = a label which is stored in ascii,and bytes 7 to 27 hold a persons name ie byte 7 holds 78 = N byte 8 holds 65 = A ... which ends up spelling NATASHA (the persons name). SO FAR SO GOOD
NOW apparently bytes 1413 to 1420 holds a monetary value (which i assume is encoded as an integer or a double). if i print the byte values, i get the following where the number before the : is the byte and the number after the : is the value.
1413 : -102
1414 : -103
1415 : -103
1416 : -103
1417 : -103
1418 : -7
1419 : -126
1420 : 64
NOW this Number is supposed to be 60720 ($607.20)
does anyone know if there is any function which will interpret the above bytes correctly as the result (which i know is correct).Your data in bytes 1413 -1420 is stored in the IEEE 754 floating-point "double format" bit layout (the format Java uses for a double),
and it has the value 607.2
BUT - it was written in littleEndian, whereas Java uses bigEndian. Makes sense, since QBasic is a MS product, and MS uses littleEndian.
You can either reverse the byte order and use Double.longBitsToDouble to create a java double, or read it with one of the methods that can read littleEndian.
If you use the longBitsToDoublemethod, it needs a long as its argument. The easiest way to do that is to create a long using the hex values of the bytes. For example, using your data converted to hex:
1420: 40
1419: 82
1418: f9
1417: 99
1416: 99
1415: 99
1414: 99
1413: 9a
long bits = 0x4082f9999999999aL;
double d = Double.longBitsToDouble(bits); -
Randomly accessing serialized objects
Is there any way to access objects written to a file randomly. Serialization basically needs accessing objects in the same order as they are writeen. but i need to access object(s) in any order.
Any suggestions on how to do so?I got this reply when i questioned the person
incharge...may be theres much more to it than i
could specify..........It could also be the case that the person in charge doesn't know that there are databases with small footprints implemented in java.
so i would be glad if soemone
could tell me what ever i plan to do with respect to
random accessing is possible or not.....I think that you should be able to write all objects to one stream, and do a reset (on the object output stream) between each write, and write the start position of each object into an index file.
I'm not sure that it will work, and having a data file + an index file is like having a small database (so why not download a database in that case)
/Kaj -
Please Come IN! IanSchneider. About random access serialized objects.
Hi,I'm a freshman.
I have a question about serialized objects.
If I useing writeObject() serialize objects into a file in order,I can gain them with readObject() in the same order. But if I want to random access these serialized objects rather than one by one,how to do?
Mr IanSchneider said "write all your objects into the same file using normal io techniques and you can still generate an index and acheive random access". It seems easy,but how to generate index and use it to acheive random access? Please write something in detail,Thank you in advance!
EXPECTING��Have a look at this class: [ [u]WARNING: I just wrote this code, it hasn't been tested ]
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;
import java.util.ArrayList;
public class SerializedObjectWriter {
private RandomAccessFile raf;
private String filepath;
private String mode;
public SerializedObjectWriter(String filePath, String mode) throws FileNotFoundException {
this.filepath = filePath;
this.mode = mode;
this.raf = new RandomAccessFile(filePath, mode);
public void writeObject(Object o, long pos) throws IOException {
raf.seek(pos);
final byte[] bytes = serialize((Serializable)o);
raf.writeInt(bytes.length);
raf.write(bytes);
public void append(Object o) throws IOException {
writeObject(o, raf.length());
public Object readObject(long pos) throws IOException, ClassNotFoundException {
raf.seek(pos);
int len = raf.readInt();
final byte[] data = new byte[len];
raf.readFully(data);
return deSerialize(data);
public Object[] readAllObjects() throws IOException, ClassNotFoundException {
int pos = 0;
final ArrayList al = new ArrayList();
while (true) {
raf.seek(pos);
final int len = raf.readInt();
final byte[] data = new byte[len];
raf.readFully(data);
al.add(deSerialize(data));
pos = (pos + len + 4);
if (pos >= raf.length()) break;
return al.toArray();
public long length() throws IOException {
return raf.length();
public void reset() throws IOException {
raf.close();
final boolean success = new File(filepath).delete();
if (!success) throw new IOException("Failed to delete file");
raf = new RandomAccessFile(filepath, mode);
public void close() throws IOException {
raf.close();
private byte[] serialize(Serializable obj) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream oos = new ObjectOutputStream(baos);
try {
oos.writeObject(obj);
} finally {
oos.close();
return baos.toByteArray();
private Object deSerialize(byte[] data) throws IOException, ClassNotFoundException {
final ByteArrayInputStream bais = new ByteArrayInputStream(data);
final BufferedInputStream bis = new BufferedInputStream(bais);
final ObjectInputStream ois = new ObjectInputStream(bis);
try {
return (Serializable) ois.readObject();
} finally {
ois.close();
public static void main(String[] args) throws Exception {
SerializedObjectWriter sor = new SerializedObjectWriter("C:\\test.ser", "rw");
sor.reset();
sor.writeObject("Test 1", 0);
sor.append("Test 2");
sor.append("Test 3");
Object[] objects = sor.readAllObjects();
for (int i = 0; i < objects.length; i++) {
System.out.println(objects);
sor.close(); -
Writing data in Random Access File
I was reading something about Random Access File coz I wanted to practice file handling in java. like, writing a data in a random access file, deleting the stored data, updating the stored data and search for a specific data.. I wasn't able to understand the example because the book gave a large program and it's not explained in detail. Is there any good tutorials that you could recommend for me?
http://www.google.com/search?q=java+RandomAccessFile+example&hl=en&sourceid=gd&rls=GGLD,GGLD:2008-06,GGLD:en
How did we get anything done before google? -
Error...java.sql.SQLException:Access denied for user
Hi,
I am getting the following error message while connecting with the MySQL .(O/S :Sun OS 5.6)
Error.....java.sql.SQLException: Invalid authorization specification: Access denied for user: 'some_user&password@localhost' (Using password: NO)
Note that i have given all permission to the user using,
GRANT ALL PRIVILEGES .......................
The code i have used to connect with the database is,
import java.io.*;
import java.sql.*;
class test
public static void main(String a[])
try
Connection con;
Statement stmt;
ResultSet rs;
Class.forName("org.gjt.mm.mysql.Driver");
con=DriverManager.getConnection(jdbc:mysql://localhost/db_name?user=some_user&password=some_pass");
stmt=con.createStatement();
//do something with resultset
catch(Exception e)
System.out.println("Exception in second try.."+e);
plese guide me on this problem to solve.
Thankz,
Bala.Hi friends...
I've read the last post...
The problem that I have is as follow....
1. I have installed on my machine MySQL 5.0 Server running
1.1 I have a database called "base1"
1.2 User "root", password "works"
1.3 I have the following sentence to connect it using JDBC
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/base1", "root", "works");
More notes:
- I use the JDBC 5.0
- My Machine is a Windows XP SP2 Pentium 3.0 512Mb
and it connects����
but I have this environment to develop applications, now that I want to connect to Production Environment happens the following:
2 The Production database is mounted on a Linux Server with MySQL 3.2.
2.1 I change the sentences as follow:
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.0.7/base1", "user", "password");
2.3 But a message appears when I run the Java Program:
java.sql.SQLException:Access denied for user: '[email protected]' (Using password: YES)
2.4 As you can see it changes the IP Address...
More notes:- I have the MySQL Query Browser and I got connection.
- The IP that display the Error Message is my Second IP configurated on my Network Properties.
- Server is a Pentium 4 3.0 GHz 2Gb Linux Red Hat 3.0
I leave this case for the spider... I hope that somebady has the solution.
What is the problem? Why the JDBC doesn't respect the IP that I wrote. -
Applet Error:java.security.AccessControlException: access denied
Hi,
I just successful deploy an business component project to oralce 8.1.6 as an EJB Session bean, and
the test of application module is successful. In the same workspace, I create an new project with
an applet(which contains only an grid control)as a client of the business component. Everything works
fine within the Applet viewer, however, when I trying to load the applet in IE5.5 I got the following
error message in java console:
Java(TM) Plug-in
Using JRE version 1.2.1
User home directory = D:\Documents and Settings\ERic
Proxy Configuration: no proxy
JAR cache enabled.
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.debugoutput read)'
Diagnostics: Silencing all diagnostic output (use -Djbo.debugoutput=console to see it)
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.logging.show.timing read)'
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.logging.show.function read)'
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.logging.show.level read)'
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.logging.show.linecount read)'
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.logging.trace.threshold read)'
Failed to query environment: 'access denied (java.util.PropertyPermission jbo.jdbc.driver.verbose read)'
java.lang.ExceptionInInitializerError: java.security.AccessControlException: access denied (java.util.PropertyPermission org.omg.CORBA.ORBClass read)
at java.security.AccessControlContext.checkPermission(Compiled Code)
at oracle.aurora.jndi.orb_dep.Orb.<clinit>(Orb.java:24)
at oracle.aurora.jndi.sess_iiop.sess_iiopURLContext.<clinit>(sess_iiopURLContext.java:9)
at javax.naming.spi.NamingManager.getURLObject(NamingManager.java:588)
at javax.naming.spi.NamingManager.getURLContext(NamingManager.java:537)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:274)
at javax.naming.InitialContext.lookup(InitialContext.java:349)
at oracle.jbo.client.remote.ejb.aurora.AuroraEJBAmHomeImpl.connectToService(AuroraEJBAmHomeImpl.java:179)
at oracle.jbo.client.remote.ejb.aurora.AuroraEJBAmHomeImpl.createSession(AuroraEJBAmHomeImpl.java:152)
at oracle.jbo.client.remote.ejb.aurora.AuroraEJBAmHomeImpl.initRemoteHome(AuroraEJBAmHomeImpl.java:123)
at oracle.jbo.client.remote.ejb.aurora.AuroraEJBAmHomeImpl.<init>(AuroraEJBAmHomeImpl.java:59)
at oracle.jbo.client.remote.ejb.aurora.AuroraEJBInitialContext.createJboHome(AuroraEJBInitialContext.java:47)
at oracle.jbo.common.JboInitialContext.lookup(JboInitialContext.java:72)
at javax.naming.InitialContext.lookup(InitialContext.java:349)
at oracle.dacf.dataset.SessionInfo._createAppModule(SessionInfo.java:2330)
at oracle.dacf.dataset.SessionInfo.connect(SessionInfo.java:1799)
at oracle.dacf.dataset.SessionInfo.openProducerObject(SessionInfo.java:1848)
at oracle.dacf.dataset.ProducerObject.open(ProducerObject.java:94)
at oracle.dacf.dataset.SessionInfo.publishSession(SessionInfo.java:1305)
at oracle.dacf.dataset.SessionInfo.publishSession(SessionInfo.java:1287)
at broadcastapplet.myBroadCastApplet.init(myBroadCastApplet.java:70)
at sun.applet.AppletPanel.run(Compiled Code)
at java.lang.Thread.run(Thread.java:479)
The Oracle 8.1.6 runs on Win2000, I put the JAR & related zip files in the same machine's IIS webserver.
Is anyone can help?
ERicHi Shaji,
Are you calling a webservice from within an Xacute Query for your applet? On first glance, it looks like a web service call is being rejected due to security permissions. If you have a webservice call (or HTTP post/get), can you test it separately with the same credentials as the webpage is using?
Regards,
Mike -
Seagate Barracuda ES ST3750640NS 750 GB - slow random access in MacPro
I installed four Seagate Barracuda ES ST3750640NS 750 GB disks in my MacPro (5GB RAM). They are mounted as two RAID-1 arrays (mirrored, no speed up).
It seems that also those (not just the non-ES, …AS version) suffers from slow speeds (<1MB) in random access with small blocks. How much this is representative of typical access with Mac OS X I cannot tell, but still this looks like some kind of incompatibility of the drives' firmware with a MacPro.
Does anyone have experience on how to correct that?
Xbench 1.3 results:
Disk Test 35.16
Sequential 93.74
Uncached Write 83.37 51.19 MB/sec [4K blocks]
Uncached Write 120.10 67.95 MB/sec [256K blocks]
Uncached Read 73.82 21.60 MB/sec [4K blocks]
Uncached Read 113.60 57.09 MB/sec [256K blocks]
Random 21.64
Uncached Write 6.46 0.68 MB/sec [4K blocks]
Uncached Write 88.67 28.39 MB/sec [256K blocks]
Uncached Read 85.41 0.61 MB/sec [4K blocks]
Uncached Read 140.90 26.14 MB/sec [256K blocks]
12" PB G4/1.2GHz- Mac Book Pro 17" - 12" iB G3/500 MHz - Mac mini G4 as server Mac OS X (10.4.8)All of the Seagate 7200.10 model hard drives have slow Random Read performance. None of the different model numbers change this fact. There is no fix for this and you will probably only notice this issue when opening a large library with Aperture or some other application that depends on a large number of small files to read.
The Randowm write performance of the Seagate 7200.10 models is actually very good. In addition, the large block copy capabilities of the 7200.10 models is exceptional.
Xbench tests make the Seagate 7200.10 model performance look much worse than it actually is. -
When trying to upload files I received the following error: "The Java Wizard cannot run. Please configure your browser to allow Java applets to access the filesystem."
If the problem is with a site that is hosted using MOVEit DMZ by Ipswitch, please notify the site owner of the issue and ask them to apply the patch that is available on the support site to resolve the issue.
This is a better resolution than downgrading your version of Java that was updated due to security issues. -
CSV vhdx files and SAN optimization - sequential or random access or...?
Is there a best practice on the SAN optimization of LUNs for CSV VHDX files - e.g. sequential vs. random access?
We recently set up a small two-node Hyper-V 2012 R2 Failover Cluster. As I was creating LUNs for the CSV vhdx files, our SAN (like most, I think) has some pre-set optimization options which are more or less sequential vs. random access. There's now the abstraction
layer of shared VHDX files and the actual data those VHDXs are being used to store. Are there any best-practices for SAN optimization in this regard?
In other words, I could see:
A. Cluster-shared VHDXs are accessed (more-or-less) based on the type of data they're used for
B. All cluster-shared VHDXs are (more-or-less) accessed sequentially
C. All cluster-shared VHDXs are (more-or-less) accessed randomly.
I have one source that says that for a relatively simple SMB setup like we have that "C" is the recommendation. I'm curious if anyone else has run into this or seen an official best-practice...?Is there a best practice on the SAN optimization of LUNs for CSV VHDX files - e.g. sequential vs. random access?
We recently set up a small two-node Hyper-V 2012 R2 Failover Cluster. As I was creating LUNs for the CSV vhdx files, our SAN (like most, I think) has some pre-set optimization options which are more or less sequential vs. random access. There's now the abstraction
layer of shared VHDX files and the actual data those VHDXs are being used to store. Are there any best-practices for SAN optimization in this regard?
In other words, I could see:
A. Cluster-shared VHDXs are accessed (more-or-less) based on the type of data they're used for
B. All cluster-shared VHDXs are (more-or-less) accessed sequentially
C. All cluster-shared VHDXs are (more-or-less) accessed randomly.
I have one source that says that for a relatively simple SMB setup like we have that "C" is the recommendation. I'm curious if anyone else has run into this or seen an official best-practice...?
There as good article published recently by Jose Barreto about CSV performance counters. See:
Cluster Shared Volume: Performance Counters
http://blogs.msdn.com/b/clustering/archive/2014/06/05/10531462.aspx
You can run DiskSPD or Intel I/O Meter yourself to see what workload you'll get @ CSV with 10+ VMs doing different I/O types. We did and you'll get
4-8KB 100% random reads and writes (just make sure you gather statistics for a long time).
So that's type of workload you could optimize your LUN @ SAN level.
StarWind Virtual SAN clusters Hyper-V without SAS, Fibre Channel, SMB 3.0 or iSCSI, uses Ethernet to mirror internally mounted SATA disks between hosts. -
This program is supposed to retrieve data from TelephoneUI's JTextFields, store the data in a RandomAccessRecord class object record and call the write method of class RandomAccessRecord to output the data.
Two questions
Is there any way to check if the data was actually written to the file without writing a new class to read the file?
How can I make it so that the file-position pointer for object output start from byte 0 for the first record and move 94 bytes after each read? Right now the file-position pointer moves 94 bytes after each read but starts from 94.
public class WriteRandomFile extends JFrame {
private RandomAccessFile output;
private TelephoneUI userInterface;
private JButton enterButton, openButton;
// set up GUI
public WriteRandomFile()
super( "Write to random access file" );
// create instance of reusable user interface TelephoneUI
userInterface = new TelephoneUI(4); // four textfields
getContentPane().add( userInterface,
BorderLayout.CENTER );
// get reference to generic task button doTask1 in TelephoneUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open..." );
// register listener to call openFile when button pressed
openButton.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// allow user to select file to open
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// add record in TelephoneUI, then close file
public void windowClosing( WindowEvent event )
if ( output != null )
addRecord();
closeFile();
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2 in TelephoneUI
enterButton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false );
// register listener to call addRecord when button pressed
enterButton.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// add record to file
public void actionPerformed( ActionEvent event )
addRecord();
} // end anonymous inner class
); // end call to addActionListener
setSize( 300, 150 );
show();
// enable user to choose file to open
private void openFile()
// display file dialog so user can select file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File Name",
JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new RandomAccessFile( fileName, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
// process exception while opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
} // end method openFile
// close file and terminate application
private void closeFile()
// close file and exit
try {
if ( output != null )
output.close();
System.exit( 0 );
// process exception while closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
// add one record to file
public void addRecord()
String fields[] = userInterface.getFieldValues();
RandomAccessRecord record =
new RandomAccessRecord();
int count = 1;
// ensure field has a value
if ( ! fields[ TelephoneUI.LASTNAME ].equals( "" ) ) {
// output values to file
try {
record.setFirstName( fields[ TelephoneUI.FIRSTNAME ] );
record.setLastName( fields[ TelephoneUI.LASTNAME ] );
record.setAddress( fields[ TelephoneUI.ADDRESS ] );
record.setPhone( Integer.parseInt( fields[ TelephoneUI.PHONENUMBER ] ) );
count = count * 94;
output.seek( count );
record.write( output );
userInterface.clearFields(); // clear TextFields
// process improper account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions while writing to file
catch ( IOException ioException ) {
closeFile();
} // end method addRecord
// execute application
public static void main( String args[] )
new WriteRandomFile();
} // end class WriteRandomFileThis program is supposed to retrieve data from
TelephoneUI's JTextFields, store the data in a
RandomAccessRecord class object record and call the
write method of class RandomAccessRecord to output
the data.
Two questions
Is there any way to check if the data was actually
written to the file without writing a new class to
read the file? Why? If the io operations are not working (and not throwing exceptions) then you might as well give up.
>
How can I make it so that the file-position pointer
for object output start from byte 0 for the first
record and move 94 bytes after each read? Right now
the file-position pointer moves 94 bytes after each
read but starts from 94.Huh? It moves 94 and you want it to move 94?
Perhaps you are just looking for the getFilePointer() and seek() methods?
>
public class WriteRandomFile extends JFrame {
private RandomAccessFile output;
private TelephoneUI userInterface;
private JButton enterButton, openButton;
// set up GUI
public WriteRandomFile()
super( "Write to random access file" );
// create instance of reusable user interface
erface TelephoneUI
userInterface = new TelephoneUI(4); // four
/ four textfields
getContentPane().add( userInterface,
BorderLayout.CENTER );
// get reference to generic task button doTask1
oTask1 in TelephoneUI
openButton = userInterface.getDoTask1Button();
openButton.setText( "Open..." );
// register listener to call openFile when
e when button pressed
openButton.addActionListener(
// anonymous inner class to handle
to handle openButton event
new ActionListener() {
// allow user to select file to open
public void actionPerformed( ActionEvent
ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing
losing event
addWindowListener(
// anonymous inner class to handle
to handle windowClosing event
new WindowAdapter() {
// add record in TelephoneUI, then close
, then close file
public void windowClosing( WindowEvent
WindowEvent event )
if ( output != null )
addRecord();
closeFile();
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2
oTask2 in TelephoneUI
enterButton =
tton = userInterface.getDoTask2Button();
enterButton.setText( "Enter" );
enterButton.setEnabled( false );
// register listener to call addRecord when
d when button pressed
enterButton.addActionListener(
// anonymous inner class to handle
to handle enterButton event
new ActionListener() {
// add record to file
public void actionPerformed( ActionEvent
ActionEvent event )
addRecord();
} // end anonymous inner class
); // end call to addActionListener
setSize( 300, 150 );
show();
// enable user to choose file to open
private void openFile()
// display file dialog so user can select file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this
( this );
// if user clicked Cancel button on dialog,
ialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null ||
fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this,
"Invalid File Name", "Invalid File
Invalid File Name",
JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new RandomAccessFile( fileName,
e( fileName, "rw" );
enterButton.setEnabled( true );
openButton.setEnabled( false );
// process exception while opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"File does not exist",
"Invalid File Name",
JOptionPane.ERROR_MESSAGE );
} // end method openFile
// close file and terminate application
private void closeFile()
// close file and exit
try {
if ( output != null )
output.close();
System.exit( 0 );
// process exception while closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
// add one record to file
public void addRecord()
String fields[] =
ds[] = userInterface.getFieldValues();
RandomAccessRecord record =
new RandomAccessRecord();
int count = 1;
// ensure field has a value
if ( ! fields[ TelephoneUI.LASTNAME ].equals(
quals( "" ) ) {
// output values to file
try {
record.setFirstName( fields[
stName( fields[ TelephoneUI.FIRSTNAME ] );
record.setLastName( fields[
stName( fields[ TelephoneUI.LASTNAME ] );
record.setAddress( fields[
ddress( fields[ TelephoneUI.ADDRESS ] );
record.setPhone( Integer.parseInt(
teger.parseInt( fields[ TelephoneUI.PHONENUMBER ] )
count = count * 94;
output.seek( count );
record.write( output );
userInterface.clearFields(); // clear
); // clear TextFields
// process improper account number or
number or balance format
catch ( NumberFormatException
Exception formatException ) {
JOptionPane.showMessageDialog( this,
"Bad account number or balance",
"Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions while writing to file
catch ( IOException ioException ) {
closeFile();
} // end method addRecord
// execute application
public static void main( String args[] )
new WriteRandomFile();
} // end class WriteRandomFile
Maybe you are looking for
-
Cannot open new tabs in same window since FF update to version 15.0
This morning, FF updated to version 15.0 when I opened it. Now, All links open in new windows instead of tabs like I have it set to do (yes, I've already checked). Also, I tried to go to about:config and NOTHING HAPPENS. The address bar is not workin
-
My computer has been spontaneously restarting itself. This last time I wasn't even at the keyboard, I was across the room. I don't know what to make of it, completely baffled. I'd love some help on this, and if it could come in layman's terms I'd
-
IPhone not recognised in iTunes after upgrading to 10.0.1
Hi, I hope someone out there can help with a problem I have with my iPhone 3GS currently running 4.1. I recently upgraded to iTunes 10.0.1 and iTunes has not worked correctly since. When I connect my iPhone to PC with a USB I receive the usual pop-up
-
Indicator-ubuntuone (my first PKGBUILD, I need review)
Hi, I've made a PKGBUILD of indicator-ubuntuone. I've used City-busz's indicator-sync as a model, but honestly I'm not sure of what I'm doing. It's my first build, I'll appreciate suggestions, corrections,... before uploading it to AUR. PKGBUILD # Ma
-
Update failed on After Effects CC. After Effects will not update!
After Effects will not update! I have tried several times clicking the update button but soon after i click the button it says 'update failed' it has an option to learn more - if clicked, this is what would appear - Please Help!