Printing to the end of a Random Access file with FileOutputStream
I need to use FileOutputStream or anything else to print to a text file. However I need to print to the "end" of the file and not write over existing content. Anybody, given the following how would I append the file "myFile.txt"? The code below writes over existing data in the file.
import java.io.*
class FileOutputDemo
public static void mani( String argsv[])
FileOutputStream out;
PrintStream p;
try
out= new FileOutputStream("myFile.txt");
p=new PrintStream( out ) ;
p.println("Write this line of text to the end of the file");
p.close();
catch(Exception e) {*Do something */}
One way is to use the RandomAccessFile class methods to append to the end of a file. Use the seek and length methods to go to the end of the file and use the appropriate method to write your data. Something like this:
try {
RandomAccessFile logFile=
new RandomAccessFile("myFile.txt", "rw");
logFile.seek(logFile.length());
logFile.writeBytes(
args[0]+"\n");
catch (Exception e) {
System.err.println("Error!");
HTH
Similar Messages
-
Random access file with object stream
Hi All,
I have saved some objects in a file using object stream. While reading the sequential read is possible for me. I want to reduce the overhead of reading whole file for getting one specific object details. Is there any way in which we can implement RandomAccessFile with object stream? or is there any other alternative of reaching specific object in the file without seqential read?is there any
other alternative of reaching specific object in the
file without seqential read?Write the objects to a database. -
Report won't print to the end of width in Oracle E-Business Suite
Hello all,
I desperately need help to setup Reports 6i layout. I created a report for a 8.3 x 11.69" and it seems fine when I print directly from Reports Developer but when I register it in Oracle E-Business Suite 11.5.10.2 it won't print to the end of page width. It always cut the print in about 3/4 of page width. I already setup the report as a text and pdf but still no success. Enlarge the width and height of the report won't help either. Anyone can suggest something to help? Thanks.Hi Clamarion,
Login as those users and check the preferences, or you can check the value from the backend (through FND_USER_PREFERENCES table).
About "Applications Start Page" profile option (Doc ID 729375.1)
https://forums.oracle.com/thread/940401
Thanks,
Hussein -
How do you get word count to print at the end of a document in Pages?
How do you get word count to print at the end of a document in Pages?
Pages v5 does not provide a user assignable word count variable. With some AppleScript, and a paste operation from the clipboard, you can have locale punctuated word count in this format: 7,803 — anywhere in your document. The following AppleScript works with Pages '09 v4.3 through Pages v5.5.2 on Yosemite.
I would suggest that you copy paste the following AppleScript into your [Apple] Script Editor and save it (suggestion) wordcnt.applescript. Then, follow this with an option+Save As… and this time set the File format to Script Bundle, or Application with hidden extension — saved to your Desktop. Provided you have a Pages document open, you are then a double-click from the ability to paste your current word count into Pages.
Note: If you have Pages word count display enabled, it will automatically count your pasted value as another word which initially may deceive on true word count at the time the script was run.
AppleScript
--- copy below this line ---
property locale : "en_US.UTF-8" -- In Terminal, use the locale command to see yours
if not ApplicationIsRunning("Pages") then
display dialog "Pages must be running to use this utility."
return quit
end if
tell application "Pages"
tell body text of front document
set wordCnt to count words
-- Don't want punctuated numbers? Remove the single quote from printf format
set the clipboard to (do shell script "export LC_ALL=" & locale & "; printf \"%'d\" " & wordCnt)
end tell
end tell
on ApplicationIsRunning(appName)
tell application "System Events" to set appNameIsRunning to exists (processes where name is appName)
return appNameIsRunning
end ApplicationIsRunning -
Footer must print at the end of the page
Hi everyone,
I have requirement in smartforms for Purchase Orde that the footer must be printed at the end of the last page irrespective of the number of items. Please help me
ThanksHi,
You have two options as suggested by all above, either go for footer in the main window with condition 'at end of table', which will print your footer at last page as soon as your table ends. this way your footer will come to the last page but will not be fixed at a position.
to fix the position of you footer at the bottom, create a separate footer window. but then you need to knw the amount of data coming on the last page, else your footer and main window content will overlap. to avoid the overlapping - you will have to count the number of line getting printed per page, this way you can know that on the last page if you have sufficient space(no. of lines) available to print the footer or not. You can check for thses conditions to suffice and get your footer printed on the last page or additional new page without overlapping.
Thanks. -
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 -
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 -
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. -
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. -
Random access file in process visability
I want to use a file in a single process with single writer or multi readers mutual exclusion, for that purpose I use number of RandomAccessFile instances over the same file which are open in read mode and are used concurrently. I also have a single RandomAccessFile open in "rw" mode which updates the file (not when it is being actively read).
I do not close the Random Access File handles at any point.
I wanted to know if the data which is being written to the file with the RandomAccessFile in rw mode will always be visible to the readers after the the write is complete?
(I am not using rws mode for performance issues, only for these readers which are in the same process).
Thanks
EitanLooking at FileChannel it has the following part in its documentation:
* The view of a file provided by an instance of this class is guaranteed
* to be consistent with other views of the same file provided by other
* instances in the same program. The view provided by an instance of this
* class may or may not, however, be consistent with the views seen by other
* concurrently-running programs due to caching performed by the underlying
* operating system and delays induced by network-filesystem protocols. This
* is true regardless of the language in which these other programs are
* written, and whether they are running on the same machine or on some other
* machine. The exact nature of any such inconsistencies are system-dependent
* and are therefore unspecified.
This looks exactly like the guarantee I need, now I've looked into RandomAccessFile.getChannel() implementation and it holds a single member of FileChannel which is initialized on demand and the next calls will return the same instance.
So the only way I see to create multiple FileChannel instances over the same file is to open multiple RandomAccessFile instances over that file and use getChannel() on each of these instances. Since FileChannel does provide this guarantee I tend to believe it relies upon a guarantee that RandomAccessFile provide, otherwise it would need some mechanism to identify that different FileChannel instances over different RandomAccessFile instances are actually over the same file in order to provide the specified guarantee.
What do you think? -
Serialize tree in random access file
I have a tree of objects, which are to be serialized. After deserialization,
each object has to know its children and its parent. Each object need not know its sibling. There are no lateral references. The number of objects in the tree will be around 2000. The depth of tree is 7. Different parts of the tree will be saved and read at different points of time in the application. While the application is running, many of the objects in the tree keep undergoing changes which have to be saved intermittantly.
I would like to use a random access file. But I have no clue how to serialize a tree of objects in a random access file which will meet the above mentioned requirements.
I would be thankful if I could get an idea to implement.I have a tree of objects, which are to be serialized.
After deserialization,
each object has to know its children and its parent.
Each object need not know its sibling. There are no
lateral references. The number of objects in the tree
will be around 2000. The depth of tree is 7.
Different parts of the tree will be saved and read at
different points of time in the application. This is an issue. When you Serialize something you serialize the entire object, not a part of it. If you're doing this then you're no longer talking about Serializing a Tree, you're talking about serializing some other thing that represents part of the tree.
While
the application is running, many of the objects in
the tree keep undergoing changes which have to be
saved intermittantly.
I would like to use a random access file. But I have
no clue how to serialize a tree of objects in a
random access file which will meet the above
mentioned requirements.
I would be thankful if I could get an idea to
implement.If you can come up with a "savable" representation of your tree that allows you to calculate where, in a file, a given part would be then you could use RandomAccessFile to read/write the thing. Just walk through your tree and seek to where you need to go in the file, then read/write the node.
I hope that made sense
Lee -
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? -
After an recent OS7 update my iPad2 requested a restore which I did, at the end my iPad jumped into "communicating with iTune" but it never communicates. I restored 3 time alreaady and I am not able to communicate with iTune to be able to use my iPad which is my working tool.
What should I do?Communicate with iTunes? What does this mean? Tell us what you are seeing on your screen and what you then try to do?
-
hello i have been trying to install i tunes 10 on to my pc but as i get to the end of installation it comes up with the message windows installer package failed contact support or vendor how do i solve this im running vista of an acer laptop many thanks
Let's try the following user tip with that one:
"There is a problem with this Windows Installer package ..." error messages when installing iTunes for Windows
Maybe you are looking for
-
Can your creative cloud account give you access to Flash Builder 4.6
Can your creative cloud account give you access to Flash Builder 4.6? 4.7 got rid of the design view, I need to get use out of the design view. Thanks
-
How to change Photoshop Elements license from Win to Mac
In February 2015, I purchased the Photoshop Elements 13 Windows version. I no longer have access to the Windows version and it was uninstalled from the Windows Platform. Can I use the serial number for the Windows version with the Mac version?
-
HT4946 How do you transfer the backup file back to the iphone?
I have just updated my iphone software and now I'm having trouble to access the backup in my computer. I have found the files but haven't got a clue of how to move that back to my phone. Any help please? Thanks, Marina
-
Merge multiple rows to get single row result
Hi, Below is the sample data from my table USERINFO- personid userid username orgid 1234 1235 TOM 1 2345 2346 HARRY 1 1111 2222 BOND 2 3333 4444 BERY 2 Now I want a query which can give me the following result- personid userid username personid u
-
Exception when trying to run xletview
Hi, I am trying to run xlet under xletview but when I try to run xletview then occurs an exception: ================================================================== Virtual Machine: Sun Microsystems Inc. Java HotSpot(TM) Client VM 1.3.1_01 Exceptio