Random Access
Hi,
When we say that the ArrayList is random access,what exactly do we mean by "Random Access"
I was half tempted to start my post out with sigh like some of the regulars around here, but then I realized how annoying and stupid that is...
Anyway, have you tried googling 'random access'? When I did, the fourth result was a fairly decent description of what random access means.
From http://www.webopedia.com/TERM/R/random_access.html
Refers to the ability to access data at random. The opposite of random access is sequential access. To go from point A to point Z in a sequential-access system, you must pass through all intervening points. In a random-access system, you can jump directly to point Z. Disks are random access media, whereas tapes are sequential access media.
If you need the item at index 2 in an ArrayList, you can retrieve it directly. For a LinkedList, you would need to iterate though the list until you reach that element. The get(int) method of LinkedList simply does the iteration for you.
Similar Messages
-
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. -
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 -
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) -
How to read a mixed text and binary random-access file?
I have a PDF file which I want to decode. The format is a mixture of binary data and text. What I need is to position the file to a particular position, and then to read from that point as a stream either a set of binary bytes or straight ASCII text. I can't see how to do this (if in fact it's possible).
I can open the file as a SeekableByteChannel and position it, but opening a stream repositions the file to the beginning - just what I don't want.
Is there any way of opening a stream from part-way through a file?I think that I gave this topic a rather misleading title. What it really should be is "How to turn a random access file into a stream"?
I realise that I can open an InputStream and skip the relevant number of characters - but this is highly inefficient on a large file where I will skipping about within the file. I need a stream so that I can apply other stream functions to it - buffering in memory will I suspect be too big. -
Xml elements random access table
hi all,
i'm having a random access table holdin the index for each xml node in a xml file, any idea how can u access the xml node directly without going through the whole xml file. i want to do this by either sax or stax, dom is not valid with my case. thanxeng_cs wrote:
hi all,
i'm having a random access table holdin the index for each xml node in a xml file, any idea how can u access the xml node directly without going through the whole xml file. i want to do this by either sax or stax, dom is not valid with my case. thanxI far as I know you could only accomplish such a thing using DOM parser alone, as DOM supports XPATH. SAX or StAX do not support XPATH, so directly going to the node in a xml is not possible using SAX or StAX. -
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); -
How to use random access file to access file in disk?
I have tried to use random access file stream to access the some files saved in disk, but not very successful. I want to know how I can find a particular file in the disk with file locator or sth else.
Suggestion is highly welcomed, if you have codes to put, I will test it.The scenerao is:
create a randomAccessfile
write 100 blank records( for future use)
open this file
write data to the records inside file
close the file.
I will try to put a testing code for you later on. -
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(); -
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. -
Why increase db env cache not improve random access performance?
I want to improve bdb random access performance.
I built a bdb with 3,000,000 records and then test random access on these records. I assign db env cache with 100M, 200M and 500M. With more cache, the cache hit ratio has been increased. However, the overall performance is NOT improved (actually performance is a little poorer with bigger cache). Why does this happen? Any way to improve the performance?
I plan to change page size later. Any suggestion on the page size setting?Below is the db_stat output of 100M cache.
Thu Feb 25 07:02:37 2010 Local time
53162 Btree magic number
9 Btree version number
Little-endian Byte order
multiple-databases Flags
2 Minimum keys per-page
4096 Underlying database page size
1007 Overflow key/data size
4 Number of levels in the tree
3000000 Number of unique keys in the tree
3000000 Number of data items in the tree
546 Number of tree internal pages
42286 Number of bytes free in tree internal pages (98% ff)
48388 Number of tree leaf pages
4939160 Number of bytes free in tree leaf pages (97% ff)
0 Number of tree duplicate pages
0 Number of bytes free in tree duplicate pages (0% ff)
3000000 Number of tree overflow pages
2259M Number of bytes free in tree overflow pages (81% ff)
0 Number of empty pages
0 Number of pages on the free list
125MB 2KB 24B Total cache size
1 Number of caches
1 Maximum number of caches
125MB 8KB Pool individual cache size
0 Maximum memory-mapped file size
0 Maximum open file descriptors
0 Maximum sequential buffer writes
0 Sleep after writing maximum sequential buffers
0 Requested pages mapped into the process' address space
9924074 Requested pages found in the cache (54%)
8125037 Requested pages not found in the cache
0 Pages created in the cache
8125037 Pages read into the cache
0 Pages written from the cache to the backing file
8094176 Clean pages forced from the cache
0 Dirty pages forced from the cache
0 Dirty pages written by trickle-sync thread
30861 Current total page count
30860 Current clean page count
1 Current dirty page count
16381 Number of hash buckets used for page location
26M Total number of times hash chains searched for a page (26174148)
132 The longest hash chain searched for a page
53M Total number of hash chain entries checked for page (53243413)
0 The number of hash bucket locks that required waiting (0%)
0 The maximum number of times any hash bucket lock was waited for (0%)
0 The number of region locks that required waiting (0%)
0 The number of buffers frozen
0 The number of buffers thawed
0 The number of frozen buffers freed
8125049 The number of page allocations
17M The number of hash buckets examined during allocations (17891415)
12 The maximum number of hash buckets examined for an allocation
8094176 The number of pages examined during allocations
1 The max number of pages examined for an allocation
0 Threads waited on page I/O
Pool File: md.bdbxml
16384 Page size
0 Requested pages mapped into the process' address space
131 Requested pages found in the cache (90%)
14 Requested pages not found in the cache
0 Pages created in the cache
14 Pages read into the cache
0 Pages written from the cache to the backing file
Pool File: md.bdbdb
4096 Page size
0 Requested pages mapped into the process' address space
9923933 Requested pages found in the cache (54%)
8125020 Requested pages not found in the cache
0 Pages created in the cache
8125020 Pages read into the cache
0 Pages written from the cache to the backing file
Pool File: compMd.bdbdb
4096 Page size
0 Requested pages mapped into the process' address space
10 Requested pages found in the cache (76%)
3 Requested pages not found in the cache
0 Pages created in the cache
3 Pages read into the cache
0 Pages written from the cache to the backing file
Default locking region information:
158 Last allocated locker ID
0x7fffffff Current maximum unused locker ID
9 Number of lock modes
1000 Maximum number of locks possible
1000 Maximum number of lockers possible
1000 Maximum number of lock objects possible
40 Number of lock object partitions
14 Number of current locks
104 Maximum number of locks at any one time
4 Maximum number of locks in any one bucket
0 Maximum number of locks stolen by for an empty partition
0 Maximum number of locks stolen for any one partition
20 Number of current lockers
35 Maximum number of lockers at any one time
13 Number of current lock objects
101 Maximum number of lock objects at any one time
3 Maximum number of lock objects in any one bucket
0 Maximum number of objects stolen by for an empty partition
0 Maximum number of objects stolen for any one partition
12M Total number of locks requested (12049088)
12M Total number of locks released (12049068)
0 Total number of locks upgraded
35 Total number of locks downgraded
0 Lock requests not available due to conflicts, for which we waited
0 Lock requests not available due to conflicts, for which we did not wait
0 Number of deadlocks
0 Lock timeout value
0 Number of locks that have timed out
0 Transaction timeout value
0 Number of transactions that have timed out
736KB The size of the lock region
0 The number of partition locks that required waiting (0%)
0 The maximum number of times any partition lock was waited for (0%)
0 The number of object queue operations that required waiting (0%)
0 The number of locker allocations that required waiting (0%)
0 The number of region locks that required waiting (0%)
3 Maximum hash bucket length
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Lock REGINFO information:
Lock Region type
5 Region ID
__db.005 Region name
0x7fc142d1c000 Original region address
0x7fc142d1c000 Region address
0x7fc142d1c138 Region primary address
0 Region maximum allocation
0 Region allocated
Region allocations: 3006 allocations, 0 failures, 0 frees, 1 longest
Allocations by power-of-two sizes:
1KB 3002
2KB 0
4KB 1
8KB 0
16KB 0
32KB 2
64KB 1
128KB 0
256KB 0
512KB 0
1024KB 0
REGION_JOIN_OK Region flags
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Lock region parameters:
32792 Lock region region mutex [0/28 0% 18243/140468027311840]
1031 locker table size
1031 object table size
824 obj_off
73640 locker_off
0 need_dd
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Lock conflict matrix:
0 0 0 0 0 0 0 0 0
0 0 1 0 1 0 1 0 1
0 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0
0 1 1 0 0 0 0 1 1
0 0 1 0 0 0 0 0 1
0 1 1 0 0 0 0 1 1
0 0 1 0 1 0 1 0 0
0 1 1 0 1 1 1 0 1
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Locks grouped by lockers:
Locker Mode Count Status ----------------- Object ---------------
42 dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
42 READ 1 HELD md.bdbxml:secondary_ handle 2
45 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
46 dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
46 READ 1 HELD md.bdbxml:secondary_ handle 4
49 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
4a dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
4a READ 1 HELD md.bdbxml:secondary_ handle 6
4d dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
4e dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
4e READ 1 HELD md.bdbxml:secondary_ handle 8
51 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
52 dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
52 READ 1 HELD md.bdbxml:secondary_ handle 10
55 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
56 dd= 0 locks held 2 write locks 0 pid/thread 19176/139654678157040
56 READ 1 HELD md.bdbxml:secondary_ handle 12
56 READ 6 HELD md.bdbxml:secondary_ handle 0
59 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
5d dd= 0 locks held 1 write locks 0 pid/thread 19176/139654678157040
5d READ 1 HELD md.bdbxml:secondary_ handle 14
60 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
61 dd= 0 locks held 2 write locks 0 pid/thread 19176/139654678157040
61 READ 1 HELD md.bdbxml:secondary_ handle 16
61 READ 2 HELD md.bdbxml:secondary_ handle 0
64 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
95 dd= 0 locks held 2 write locks 0 pid/thread 19176/139654678157040
95 READ 1 HELD md.bdbdb:md.db handle 2
95 READ 1 HELD md.bdbdb:md.db handle 0
98 dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
99 dd= 0 locks held 2 write locks 0 pid/thread 19176/139654678157040
99 READ 1 HELD compMd.bdbdb:compMd.bdb handle 2
99 READ 1 HELD compMd.bdbdb:compMd.bdb handle 0
9c dd= 0 locks held 0 write locks 0 pid/thread 19176/139654678157040
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Locks grouped by object:
Locker Mode Count Status ----------------- Object ---------------
61 READ 1 HELD md.bdbxml:secondary_ handle 16
4a READ 1 HELD md.bdbxml:secondary_ handle 6
46 READ 1 HELD md.bdbxml:secondary_ handle 4
42 READ 1 HELD md.bdbxml:secondary_ handle 2
56 READ 6 HELD md.bdbxml:secondary_ handle 0
61 READ 2 HELD md.bdbxml:secondary_ handle 0
5d READ 1 HELD md.bdbxml:secondary_ handle 14
56 READ 1 HELD md.bdbxml:secondary_ handle 12
52 READ 1 HELD md.bdbxml:secondary_ handle 10
4e READ 1 HELD md.bdbxml:secondary_ handle 8
95 READ 1 HELD md.bdbdb:md.db handle 0
95 READ 1 HELD md.bdbdb:md.db handle 2
99 READ 1 HELD compMd.bdbdb:compMd.bdb handle 0
99 READ 1 HELD compMd.bdbdb:compMd.bdb handle 2 -
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 -
Why do I need to define these in std for my random access iterator???
Hi guys,
I have written my own iterator class, to support 1-d slices of 2-d matrices, 2-d slices of 3-d matrices, etc.
At first I wrote the class as a bidirectional iterator, but then I needed to extend it to random access so that I could pass these iterators to std::sort etc. No problem, I thought, I just needed to add friend operators for "iterator-iterator" and "iterator+/-distance".
So, I did that and tested the code with VS6 and various versions of g++, with no problems. Isn't STL great!
But I had endless problems with Studio 10. It kept griping that various mostly-internal-looking template functions were not defined. The only way I could get it to work was to define these:
#if (defined __SUNPRO_CC) && (__SUNPRO_CC <= 0x570)
namespace std
template<typename T> // Sigh
typename matrixit<T>::
difference_type distance(const matrixit<T>& a, const matrixit<T>& b) {
return b-a;
template<typename T> // WTF?
T* __value_type(const matrixit<T>&) {
return static_cast<T*>(0);
template<typename T> // WTF?
typename matrixit<T>::
difference_type* __distance_type(const matrixit<T>&) {
return static_cast<typename matrixit<T>::difference_type*>(0);
template<typename T> // WTF?
typename matrixit<T>::
iterator_category __iterator_category(const matrixit<T>&) {
return typename matrixit<T>::iterator_category();
#endif
Why do I have to do this, or am I missing something in my iterator class (eg, typedefs), or do I need to derive it from something? Here is what it looks like:
template<typename T>
class matrixit
public:
typedef T& reference;
typedef T* pointer;
typedef T value_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef std::random_access_iterator_tag iterator_category;
Ta, Simon.Come on, it is not that hard to work around the limitations of Cstd. For what you show here, you can use:
namespace std {
template <class Iterator> struct iterator_traits
typedef typename Iterator::value_type value_type;
typedef typename Iterator::difference_type difference_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
typedef typename Iterator::iterator_category iterator_category;
template <class T> struct iterator_traits<T*>
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef T& reference;
typedef random_access_iterator_tag iterator_category;
template <class T> struct iterator_traits<const T*>
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef const T* pointer;
typedef const T& reference;
typedef random_access_iterator_tag iterator_category;
template <class ForwardIterator>
inline ptrdiff_t
distance (ForwardIterator first, ForwardIterator last)
ptrdiff_t n = 0;
__distance(first, last, n,
iterator_traits<ForwardIterator>::iterator_category());
return n;
template <class InputIterator, class T>
inline typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& value)
typename iterator_traits<InputIterator>::difference_type result;
count(first,last,value,result);
return result;
template <class InputIterator, class Predicate>
inline typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, Predicate pred)
typename iterator_traits<InputIterator>::difference_type result;
count_if(first,last,pred,result);
return result;
template < class T >
inline typename T::value_type*
__value_type (const T&)
{ return (typename T::value_type*)(0); }
template < class T >
inline typename T::difference_type*
__distance_type(const T&)
{ return (typename T::difference_type*)(0); }
template < class T >
inline typename T::iterator_category
__iterator_category (const T&)
typename T::iterator_category tmp;
return tmp;
} // namespace std
For the missing constructor of vector with iterators, you can simply use std::copy with a back_insert_iterator.
The hardest thing to work around is probably the missing conversion between std::pair of various types (for instance with various constness when you use std::map), but it can still be handled by always specifying the type of the pair instead of relying on std::make_pair.
And if there is a thing you really don't know how to work around, you can always ask here...
Maybe you are looking for
-
HDMI cable - Plus Pay TV with HDMI cable. How to correct?
Today i purchased Apple tv and was told to buy a HDMI cable which i did. My problem is my tv has 1 input and that input currently has HDMI cable connected to the Austar unit (pay TV). Any ideas how to correct this please? i.e. double adapter etc.
-
Firmware upgrade for WRT54G v7
is there no firmware upgrade for WRT54G v7? i didn't even find version7 as listed in linksys page for routers....
-
Check require for duplicate MIRO Credit memo
Hi expert in my system, duplicate check is working for MIRO(Vendor invoice) but not for MIRO Credit memo.Why it is happened and what is sollution for duplicate check -MIRO Credit memo?Please let me know that. regardss sachin
-
Error in Weblogic server while deploying a sample cartridge
hi all I am getting below error while deploying a sample cartridge to the web logic. ####<Jun 27, 2012 4:32:40 PM GMT+05:30> <Warning> <cartridgemanagement> <ww021006> <AdminServer> <[ACTIVE] ExecuteThread: '6' for queue: 'weblogic.kernel.Default (se
-
Address Book Archive not working
I am trying to move my Address Book from my G4 to my MacBook Pro (both running 10.5.8). The archive creates, I move it over on a USB stick, and then use import/address book archive. It gives me a popup saying that reverting to the archive will wipe o