Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2006

Tip: Looking for answers? Try searching our database.

Random Access File IO

Thread view: 
GreenMountainBoy - 10 Nov 2006 15:43 GMT
HI,

I really would appreciateit if someone could provide me with some
advice (sample code) on how to write a simple random access file I/O
program in java.

the record structure is

public employee {

int iRecordNumber;

String sName;

double dSalary;

}

HOW DO I CREATE A SIMPLE PROGRAM TO DO RANDOM ACCESS FILE I/O?

I need to be able to create these records from the keyboard, and then
write them to a random access file using the iRecordNumber as the key.
Part of the problem is that the sName field should be fixede at 25
characters in length, but I dont know how to do that.

Then, I need to be able to read back in a record by entering its
iRecordNumber from the keyboard,

and ideally, should be able to delete a random record.

Thanks for your help - any assistance would be very much appreciated!

GreenMountainBoy
Ian Wilson - 10 Nov 2006 16:49 GMT
> I really would appreciateit if someone could provide me with some
> advice (sample code) on how to write a simple random access file I/O
> program in java.

See http://java.sun.com/docs/books/tutorial/essential/io/rafs.html

> the record structure is
>
> public employee {

More Javaish would be

public class Employee {

> int iRecordNumber;
>
> String sName;
>
> double dSalary;

Generally I find you don't need to prefix variable names with a type
indicator. This is because the Java compiler does a pretty good job of
preventing you from using the wrong data type in the wrong places.

> }
>
> HOW DO I CREATE A SIMPLE PROGRAM TO DO RANDOM ACCESS FILE I/O?

PLEASE DON'T SHOUT! IT MAKES FOLK IRRITABLE!

> I need to be able to create these records from the keyboard, and then
> write them to a random access file using the iRecordNumber as the key.
> Part of the problem is that the sName field should be fixede at 25
> characters in length, but I dont know how to do that.

Maybe you could use String.format() when writing it.
A lot of people seem to use .length() and add the required number of " "
to a String (or better to a StringBuffer or char[]).
All the above can be found by Googling for Java String pad.

> Then, I need to be able to read back in a record by entering its
> iRecordNumber from the keyboard,
>
> and ideally, should be able to delete a random record.
>
> Thanks for your help - any assistance would be very much appreciated!

You multiposted to c.l.j.p because you didn't get an answer here within
ten minutes. That sort of impatient behaviour may annoy lots of people
and make them less likely to help you.

I find this guide helpful in working out how to get answers in
newsgroups: http://www.catb.org/~esr/faqs/smart-questions.html

My advice is, if you don't know about the following, make an effort to
find out: Top-posting, multi-posting, quoting and trimming.

Good luck!
GreenMountainBoy - 10 Nov 2006 21:10 GMT
sorry about the load and abrasive style.....

> > I really would appreciateit if someone could provide me with some
> > advice (sample code) on how to write a simple random access file I/O
[quoted text clipped - 54 lines]
>
> Good luck!
RedGrittyBrick - 10 Nov 2006 20:17 GMT
> HOW DO I CREATE A SIMPLE PROGRAM TO DO RANDOM ACCESS FILE I/O?

Java has java.io.RandomAccessFile.
Charles Hottel - 11 Nov 2006 03:35 GMT
> HI,
>
[quoted text clipped - 29 lines]
>
> GreenMountainBoy

Here is an example froma Mike Murach book:

import java.io.*;
import java.util.*;

public class BookIO{
private static Book book = null;
private static String[] codes = null;
private static RandomAccessFile randomFile = null;

private static final File BOOK_FILE = new File("books.dat");
private static final int CODE_SIZE = 4;
private static final int TITLE_SIZE = 20;
private static final int RECORD_SIZE = CODE_SIZE*2 + TITLE_SIZE*2 + 8;

public static void open() throws IOException{
 randomFile = new RandomAccessFile(BOOK_FILE, "rw");
 codes = readCodes();
}

public static void close(){
 try{
  randomFile.close();
 }
 catch(IOException e){
  System.out.println("I/OException thrown when closing file.");
 }
}

public static int getRecordCount() throws IOException{
 long length = BOOK_FILE.length();
 int recordCount = (int) (length / RECORD_SIZE);
 return recordCount;
}

public static String readString(DataInput in, int length)
throws IOException{
 String s = "";
 int i = 0;
 while (i < length){
  char c = in.readChar();
  if (c!=0)
   s += c;
  i++;
 }
 return s;
}

public static Book readRecord(int recordNumber) throws IOException{
 randomFile.seek((recordNumber-1) * RECORD_SIZE);
 String code = readString(randomFile, CODE_SIZE);
 String title = readString(randomFile, TITLE_SIZE);
 double price = randomFile.readDouble();
 book = new Book(code, title, price);
 return book;
}

public static Book readRecord(String bookCode) throws IOException{
 int recordNumber = getRecordNumber(bookCode);
 book = readRecord(recordNumber);
 return book;
}

public static int getRecordNumber(String bookCode) throws IOException{
 int match = -1;
 int i = 0;
 boolean flag = true;
 while ((i < getRecordCount()) && (flag==true)){
  if (bookCode.equals(codes[i])){
   match = i+1;
   flag = false;
  }
  i++;
 }
 return match;
}

public static String[] readCodes() throws IOException{
 codes = new String[getRecordCount()];
 for (int i = 0; i < getRecordCount(); i++){
  randomFile.seek(i * RECORD_SIZE);
  codes[i] = readString(randomFile, CODE_SIZE);
 }
 return codes;
}

public static String[] readTitles() throws IOException{
 String[] titles = new String[getRecordCount()];
 for (int i = 0; i < getRecordCount(); i++){
  randomFile.seek(i * RECORD_SIZE + 8);
  titles[i] = readString(randomFile, TITLE_SIZE);
 }
 return titles;
}

public static void writeString(DataOutput out, String s, int length)
throws IOException{
 for (int i = 0; i < length; i++){
  if (i < s.length())
   out.writeChar(s.charAt(i));
  else
   out.writeChar(0);
 }
}

public static void writeRecord(Book book, int recordNumber)
throws IOException{
 randomFile.seek((recordNumber-1) * RECORD_SIZE);
 writeString(randomFile, book.getCode(), CODE_SIZE);
 writeString(randomFile, book.getTitle(), TITLE_SIZE);
 randomFile.writeDouble(book.getPrice());
}

public static Book moveFirst() throws IOException{
 book = readRecord(1);
 return book;
}

public static Book movePrevious() throws IOException{
 //add code to handle if Prev button clicked on first record.
 int recordNumber = getRecordNumber(book.getCode());
 book = readRecord(recordNumber - 1);
 return book;
}

public static Book moveNext() throws IOException{
 //add code to handle if Next button clicked on last record.
 int recordNumber = getRecordNumber(book.getCode());
 book = readRecord(recordNumber + 1);
 return book;
}

public static Book moveLast() throws IOException{
 int lastRecordNumber = getRecordCount();
 book = readRecord(lastRecordNumber);
 return book;
}

public static void addRecord(Book addBook) throws IOException{
 writeRecord(addBook, getRecordCount() + 1);
 close();
 open();
}

public static void updateRecord(Book book) throws IOException{
 int recordNumber = getRecordNumber(book.getCode());
 //record needs to be written to file
}

public static void deleteRecord(String bookCode) throws IOException{
 int recordNumber = getRecordNumber(bookCode);
 Vector books = new Vector();
 for (int i = 0; i< getRecordCount(); i++){
  books.add(readRecord(i+1));
 }
 books.remove(recordNumber-1);
 randomFile.setLength(RECORD_SIZE *(getRecordCount() -1));
 for (int i = 0; i<books.size(); i++){
  writeRecord((Book)books.elementAt(i),i+1);
 }
 if (recordNumber < getRecordCount())
  book = readRecord(recordNumber);
 else
  book = readRecord(getRecordCount()-1);
 close();
 open();
}
}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.