Randomaccessfile, writing an update to the file?

Hi,
I'm working on an app that uses a randomaccessfile (student.dat) and I have it so it will write info to the dat file & I can search thru what I entered..... now I need to add the ability to update a record in the dat. The student info is just basic name & address. So I need to be able to update an address change for a given record.
I looked at the documentation online but I'm not understanding how you capture the reference point in the file and modify it.... does anyone have a good example or does anyone out there know how to explain how to do it to me??
My file is here below that I need to add the update functionality to (and the 2 accompaning files)...... I already inserted my Update button on the second panel where it needs to reside. Now I need to add the update functionality to the button.
Anyone have any suggestions/explanations on how to add this fnctionality or know a working example I can reference?? Any help would be great appreciated.... thanks.
// StudentRecords.java: Store and read data
// using RandomAccessFile
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class StudentRecords extends JFrame {
  // Create a tabbed pane to hold two panels
  private JTabbedPane jtpStudent = new JTabbedPane();
  // Random access file for access the student.dat file
  private RandomAccessFile raf;
  /** Main method */
  public static void main(String[] args) {
    StudentRecords frame = new StudentRecords();
    frame.pack();
    frame.setTitle("Test RandomAccessFile");
    frame.setVisible(true);
  /** Default constructor */
  public StudentRecords() {
    // Open or create a random access file
    try {
      raf = new RandomAccessFile("student.dat", "rw");
    catch(IOException ex) {
      System.out.print("Error: " + ex);
      System.exit(0);
    // Place buttons in the tabbed pane
    jtpStudent.add(new RegisterStudent(raf), "Register Student");
    jtpStudent.add(new ViewStudent(raf), "View Student");
    // Add the tabbed pane to the frame
    getContentPane().add(jtpStudent);
// Register student panel
class RegisterStudent extends JPanel implements ActionListener {
  // Button for registering a student
  private JButton jbtRegister;
  // Student information panel
  private StudentPanel studentPanel;
  // Random access file
  private RandomAccessFile raf;
  public RegisterStudent(RandomAccessFile raf) {
    // Pass raf to RegisterStudent Panel
    this.raf = raf;
    // Add studentPanel and jbtRegister in the panel
    setLayout(new BorderLayout());
    add(studentPanel = new StudentPanel(),
      BorderLayout.CENTER);
    add(jbtRegister = new JButton("Register"),
      BorderLayout.SOUTH);
    // Register listener
    jbtRegister.addActionListener(this);
  /** Handle button actions */
//   JFileChooser fc;
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbtRegister) {
      Student student = studentPanel.getStudent();
      try {
        raf.seek(raf.length());
        student.writeStudent(raf);
      catch(IOException ex) {
        System.out.print("Error: " + ex);
// View student panel
class ViewStudent extends JPanel implements ActionListener {
  // Buttons for viewing student information
  private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast, jbtUpdate;
  // Random access file
  private RandomAccessFile raf = null;
  // Current student record
  private Student student = new Student();
  // Create a student panel
  private StudentPanel studentPanel = new StudentPanel();
  // File pointer in the random access file
  private long lastPos;
  private long currentPos;
  public ViewStudent(RandomAccessFile raf) {
    // Pass raf to ViewStudent
    this.raf = raf;
    // Panel p to hold four navigator buttons
    JPanel p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(jbtFirst = new JButton("First"));
    p.add(jbtNext = new JButton("Next"));
    p.add(jbtPrevious = new JButton("Previous"));
    p.add(jbtLast = new JButton("Last"));
    p.add(jbtUpdate = new JButton("Update"));
    // Add panel p and studentPanel to ViewPanel
    setLayout(new BorderLayout());
    add(studentPanel, BorderLayout.CENTER);
    add(p, BorderLayout.SOUTH);
    // Register listeners
    jbtFirst.addActionListener(this);
    jbtNext.addActionListener(this);
    jbtPrevious.addActionListener(this);
    jbtLast.addActionListener(this);
    jbtUpdate.addActionListener(this);
  /** Handle navigation button actions */
  public void actionPerformed(ActionEvent e) {
    String actionCommand = e.getActionCommand();
    if (e.getSource() instanceof JButton) {
      try {
        if ("First".equals(actionCommand)) {
          if (raf.length() > 0)
            retrieve(0);
        else if ("Next".equals(actionCommand)) {
          currentPos = raf.getFilePointer();
          if (currentPos < raf.length())
            retrieve(currentPos);
        else if ("Previous".equals(actionCommand)) {
          currentPos = raf.getFilePointer();
          if (currentPos > 0)
            retrieve(currentPos - 2*2*Student.RECORD_SIZE);
        else if ("Last".equals(actionCommand)) {
          lastPos = raf.length();
          if (lastPos > 0)
            retrieve(lastPos - 2*Student.RECORD_SIZE);
        else if ("Update".equals(actionCommand)) {
     //     raf.writeChars(student.dat);     //HOW DO I UPDATE THE FILE????????????????
      catch(IOException ex) {
        System.out.print("Error: " + ex);
  /** Retrieve a record at specified position */
  public void retrieve(long pos) {
    try {
      raf.seek(pos);
      student.readStudent(raf);
      studentPanel.setStudent(student);
    catch(IOException ex) {
      System.out.print("Error: " + ex);
// This class contains static methods for reading and writing
// fixed length records
class FixedLengthStringIO {
  // Read fixed number of characters from a DataInput stream
  public static String readFixedLengthString(int size,
    DataInput in) throws IOException {
    char c[] = new char[size];
    for (int i=0; i<size; i++)
      c[i] = in.readChar();
    return new String(c);
  // Write fixed number of characters (string s with padded spaces)
  // to a DataOutput stream
  public static void writeFixedLengthString(String s, int size,
    DataOutput out) throws IOException {
    char cBuffer[] = new char[size];
    s.getChars(0, s.length(), cBuffer, 0);
    for (int i = s.length(); i < cBuffer.length; i++)
      cBuffer[i] = ' ';
    String newS = new String(cBuffer);
    out.writeChars(newS);
}Student Panel....................
// StudentPanel.java: Panel for displaying student information
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class StudentPanel extends JPanel {
  JTextField jtfName = new JTextField(32);
  JTextField jtfStreet = new JTextField(32);
  JTextField jtfCity = new JTextField(20);
  JTextField jtfState = new JTextField(2);
  JTextField jtfZip = new JTextField(5);
  /** Construct a student panel */
  public StudentPanel() {
    // Set the panel with line border
    setBorder(new BevelBorder(BevelBorder.RAISED));
    // Panel p1 for holding labels Name, Street, and City
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(3, 1));
    p1.add(new JLabel("Name"));
    p1.add(new JLabel("Street"));
    p1.add(new JLabel("City"));
    // Panel jpState for holding state
    JPanel jpState = new JPanel();
    jpState.setLayout(new BorderLayout());
    jpState.add(new JLabel("State"), BorderLayout.WEST);
    jpState.add(jtfState, BorderLayout.CENTER);
    // Panel jpZip for holding zip
    JPanel jpZip = new JPanel();
    jpZip.setLayout(new BorderLayout());
    jpZip.add(new JLabel("Zip"), BorderLayout.WEST);
    jpZip.add(jtfZip, BorderLayout.CENTER);
    // Panel p2 for holding jpState and jpZip
    JPanel p2 = new JPanel();
    p2.setLayout(new BorderLayout());
    p2.add(jpState, BorderLayout.WEST);
    p2.add(jpZip, BorderLayout.CENTER);
    // Panel p3 for holding jtfCity and p2
    JPanel p3 = new JPanel();
    p3.setLayout(new BorderLayout());
    p3.add(jtfCity, BorderLayout.CENTER);
    p3.add(p2, BorderLayout.EAST);
    // Panel p4 for holding jtfName, jtfStreet, and p3
    JPanel p4 = new JPanel();
    p4.setLayout(new GridLayout(3, 1));
    p4.add(jtfName);
    p4.add(jtfStreet);
    p4.add(p3);
    // Place p1 and p4 into StudentPanel
    setLayout(new BorderLayout());
    add(p1, BorderLayout.WEST);
    add(p4, BorderLayout.CENTER);
  /** Get student information from the text fields */
  public Student getStudent() {
    return new Student(jtfName.getText().trim(),
                       jtfStreet.getText().trim(),
                       jtfCity.getText().trim(),
                       jtfState.getText().trim(),
                       jtfZip.getText().trim());
  /** Set student information on the text fields */
  public void setStudent(Student s) {
    jtfName.setText(s.getName());
    jtfStreet.setText(s.getStreet());
    jtfCity.setText(s.getCity());
    jtfState.setText(s.getState());
    jtfZip.setText(s.getZip());
}Student file............
// Student.java: Student class encapsulates student information
import java.io.*;
public class Student implements Serializable {
  private String name;
  private String street;
  private String city;
  private String state;
  private String zip;
  // Specify the size of five string fields in the record
  final static int NAME_SIZE = 32;
  final static int STREET_SIZE = 32;
  final static int CITY_SIZE = 20;
  final static int STATE_SIZE = 2;
  final static int ZIP_SIZE = 5;
  // the total size of the record in bytes, a Unicode
  // character is 2 bytes size
  final static int RECORD_SIZE =
    (NAME_SIZE + STREET_SIZE + CITY_SIZE + STATE_SIZE + ZIP_SIZE);
  /** Default constructor */
  public Student() {
  /** Construct a Student with specified name, street, city, state,
     and zip
  public Student(String name, String street, String city,
    String state, String zip) {
    this.name = name;
    this.street = street;
    this.city = city;
    this.state = state;
    this.zip = zip;
  /** Return name */
  public String getName() {
    return name;
  /** Return street */
  public String getStreet() {
    return street;
  /** Return city */
  public String getCity() {
    return city;
  /** Return state */
  public String getState() {
    return state;
  /** Return zip */
  public String getZip() {
    return zip;
  /** Write a student to a data output stream */
  public void writeStudent(DataOutput out) throws IOException {
    FixedLengthStringIO.writeFixedLengthString(
      name, NAME_SIZE, out);
    FixedLengthStringIO.writeFixedLengthString(
      street, STREET_SIZE, out);
    FixedLengthStringIO.writeFixedLengthString(
      city, CITY_SIZE, out);
    FixedLengthStringIO.writeFixedLengthString(
      state, STATE_SIZE, out);
    FixedLengthStringIO.writeFixedLengthString(
      zip, ZIP_SIZE, out);
  /** Read a student from data input stream */
  public void readStudent(DataInput in) throws IOException {
    name = FixedLengthStringIO.readFixedLengthString(
      NAME_SIZE, in);
    street = FixedLengthStringIO.readFixedLengthString(
      STREET_SIZE, in);
    city = FixedLengthStringIO.readFixedLengthString(
      CITY_SIZE, in);
    state = FixedLengthStringIO.readFixedLengthString(
      STATE_SIZE, in);
    zip = FixedLengthStringIO.readFixedLengthString(
      ZIP_SIZE, in);

Advise sounds strikingly similar to what I mentioned
page b4. Look, can you post the entire class in code
tags ... and the entire file as well?@Bill,
Yes, I read yours but (sorry, its hard to answer multiple replies in these forums) but I could not understand some of what you suggested. If you look at the //???? lines I commented on your code below you'll see where I'm lost on what you are doing there. You also mentioned a "marker"... is that the currentPos thing in the code of mine, to get the current position?
Both you and Andrew suggested classes to some extent but I'm not sure how to it or what goes in it. If you look at my code paste above the buttons seem to have everything in the action, not a class, other than the register button on the other pane (which has a write method in studentpanel.java).
I'm trying to follow/implement what u guys have been suggesting... but my brain just is not wrapping around the what I should type & where..... :-( Got any further explanation/demonstration of what I should be doing?? Sorry, I'm not that skilled of a programmer yet...
int curr_ptr = 0,
prev_ptr = 0;
String marker = "ADDRS=",
address="My new address",
record = null;
while ( ( record = raf.readLine() ) != null ) {   //????
curr_ptr = raf.getFilePointer();
if ( ( idx = record.indexOf("marker") ) != -1 ) {   //????
record = record.substring( 0, 6 ) + address;  //????
raf.seek( prev_ptr );
raf.writeBytes( record );
curr_ptr = raf.getFilePointer();
raf.seek(curr_ptr);
}

Similar Messages

  • Error message:The iPod cannot be updated. The file or directory corrupted..

    HELP!! error message: "The iPod cannot be updated. The file or directory is corrupted and unreadable."
    What do i do?!?! it wont let me update or ANYTHING, it wont even let me delete anything off of it. Its a 5th generation 30 gig about 1 1/2 years old. HELP?!?!
    5th generation 30 gig   Windows XP  

    Hi swiss22!
    Have you tried restoring your iPod? For instructions and info on how to restore an iPod, see this:
    Restoring iPod to factory settings
    If a restore doesn't help, then take a look at this post by Da Gopha:
    Da Gopha: Info on iTunes "corrupt" error messages
    -Kylene

  • TS3694 help, im trying to update my iphone but it kept saying connect to itunes, i have updated, run the file over and over but its still stuck to connect to itunes, wat can i do? thanx

    help, im trying to update my iphone but it kept saying connect to itunes, i have updated, run the file over and over but its still stuck to connect to itunes, wat can i do? thanx

    See Here  >  http://support.apple.com/kb/HT1808
    You may need to try this More than Once...
    Be sure to Follow ALL the Steps...
    But... if the Device has been Modified... this will Not necessarily work

  • "This ipod cannot be updated. The files are corrupted and unreadable"

    This message now appears when I connect my ipod to itunes....
    "This ipod cannot be updated. The files are corrupted and unreadable"
    The ipod still works and charges, but it will no longer let me add new files to it. The contents of my ipod are still displayed as usual on itunes, so it obviously is reading it to some degree. It advises me to run a chkdsk utility, but I have no idea how to do this.
    Has anyone encountered a similar problem? Does anyone know how I can fix this problem?
    Many thanks

    If your iPod is corrupt then you have no choice but to restore it.
    Before you do that, you may have some success getting the music off it and onto your hard drive again.
    Check out the instructions/suggestions here.
    Music from iPod to computer.

  • IPod cannot be updated because the file cannot be found

    Just purchased a new 5th gen. 30gb iPod, and when plugged into my laptop & iTunes, I get the error message that "so and so's iPod cannot be updated - the file cannot be found." Then the iPod drops out of itunes, but stays in My Computer. Any way to fix this?

    I just dealt with the same problem. None of the answers people gave to the problem worked!
    Whatever it is that you're trying to put into your iPod... make sure that the file is located in your "My Music" file first.
    Basically, when you get that message double check and if what you selected isn't in "My Music" drag and drop into it and try again.
    I hope that helped!
    I know... so frustrating.

  • IPod could not be updated because the file is corrupt.

    iTunes refueses to update my iPod touch to 2.0.1. The download appears in the que as 1.5kb (which it certainly isn't), and then after downloading, a message tells me the iPod can't update because the firmware file is corrupt. It also says to reconnect and try again, but that doesn't do anything. HELLLPPP.

    See if anything here helps: What to do if iPod can't be updated because
    the firmware file was corrupt or not found
    That was the answer. A very easy fix when you know what to do. Thank you for your help.

  • Updates  say the files are corrupt

    Hi
    my girlfriends MacBook is running OS x lion 10.7.4,when she tries to download the updates it never manages to to install them ,we just get a 'Files may have been corrupted during the download ' or something similar, then it just restarts .This has happened before but after a few attempts it updated sucessfully.
    Can anyone help us
    Barkin71

    You´re better off placing questions regarding Lion updates in the Lion community.

  • OS update 10.9.2 Can't update computer The file couldn't be saved because I don't have permission

    Got my Macbook air last week
    10.9.2 is my first update
    Getting this error message
    "The file couldn't be saved because you don't have permission"

    Snce it's a new machine, contact Apple's Support, formerly Apple Express Lane and let them sort things out for you. BTW, many missing details, such as when are you getting that message? which kind of account are you logged into while trying to update?.

  • I cannot update Firefox, the file is damaged it tells to me, or was not correctly sent

    There is a recommended updating of Firefox but I dont have the access to install it in my computer. Contact system adminstrator?
    I dont have any!! Or it tells me the file is damaged, not correctly sent. What to do?

    Download latest Firefox version from one of these links:
    * http://www.mozilla.com/en-US/firefox/new/
    * http://www.mozilla.com/en-US/firefox/all.html
    Installing Firefox on Mac
    * https://support.mozilla.com/en-US/kb/Installing%20Firefox%20on%20Mac
    Check and tell if its working.

  • Software updates - 'can't be updated as the file won't expand and may be corrupted'

    I haven't managed to update any software on my MBP for weeks as I get the above message. I thought it was a matter of space so I cleared some, and tried to update one at a time but still no joy.
    Now tried downloading diectly from Downloads site but get the message 'invalid checksum'
    What should I do? Please??

    I haven't managed to update any software on my MBP for weeks as I get the above message. I thought it was a matter of space so I cleared some, and tried to update one at a time but still no joy.
    Now tried downloading diectly from Downloads site but get the message 'invalid checksum'
    What should I do? Please??

  • "The Ipod cannot be updated. The file or directory is corrupted and..

    ..unreadable"
    what does this mean?? i can't add new songs.

    If your iPod is corrupt then you have no choice but to restore it.
    Before you do that, you may have some success getting the music off it and onto your hard drive again.
    Check out the instructions/suggestions here.
    Music from iPod to computer.

  • I have a Pages file that I created on my iPad that I used iCloud to store. There are no backups anywhere of this file. The file is stuck on updating on iCloud and on the iPad the file is inaccessible. There is a black bar over it which greys the file out.

    I have a Pages file that I used my iPad to create. iCloud backed this file up to its server. The problem is that my iPad somehow locked itself. I had to restore it, the file was lost on the iPad, and when I went back to iCloud to retrieve the file it said it was Updating. The file is showing on my iPad, but it is greyed out with a black bar across the bottom of it. I have been working on this file for months, and I am not about to lose it! Please can someone tell me how I can get my file to download at least to my iMac.
    This file has worked perfectly in the past, and what I didn't realise when the iPad was locked down was that the Airplane Mode was on, to save battery. If that had been on it would have synced it again.
    Can anyone help me? I'm supposed to be sending this file (completed) off to a company in three days.
    Thanks

    On the iPad tap Settings > iCloud
    Toggle Documents & Data off then back on then restart your iPad.
    Hold the On/Off Sleep/Wake button down until the red slider appears. Slide your finger across the slider to turn off iPhone. To turn iPhone back on, press and hold the On/Off Sleep/Wake button until the Apple logo appears.
    On the iMac open System Preferences > iCloud
    Deselect the box next to Documents & Data then reselect it then restart your iMac.

  • File adapter Need to wait When Other Applicatio is writing the file

    Hi All,
    This is File to File Interface, iam using NFS here.
    While other application is writing the file to the Folder, XI Sender File Adapter shld wait for certain time and then pick it up.
    We have the Option " MSecs to Wait Before Modification Check" on File Sender Advanced TAB.
    But it is no Use, it is not behaving correctly.
    Please assist me on this
    Regards

    Hey Vamsi,
    I think you're good to go here. The behaviour is exactly as it should be. The polling interval takes priority when there is no file there but when there is a file there the modification check will take priority over polling interval so it will still wait the mandatory 2 minutes to ensure that no modification is taking place & that's exactly what you want. You don't want to pick up an incomplete file irrespective of when it was put there. So there will always be just over a 2 minute delay (or whatever you set the Msecs value to + a few seconds depending on where the polling cycle is when a file is written out but a max of 2 minutes & 19 seconds delay) when there is a file there but at least you'll have consistent data. If there is no file there the adapter will just poll every 20 seconds until a file arrives.
    The 2 minute 'wait' step is exactly that. The adapter will see the file then wait 2 minutes & probably does a timestamp comparison or something. It doesn't do a modification check within those 2 minutes. Having said that, I don't see why you can't reduce the Msecs interval. My reasoning is that you basically want to establish whether it's still being wriiten out before you pick it up. Even if you set it to 5 seconds you should still be able to pickup whether the file is being modified (I'm assuming that the check is doing a timestamp comparison). That will significantly reduce your time wait period.
    My assumption on the timestamp comparison was wrong It's actually does a comparison on file size when it reads the data in, see SAP Note (Point 3): [http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes/sdn_oss_bc_xi/~form/handler%7b5f4150503d3030323030363832353030303030303031393732265f4556454e543d444953504c4159265f4e4e554d3d383231323637%7d]
    Another suggestion made on the note: Get the writing application to write the file out with an extension different to the one you're polling for. Then, after they have completed writing out the file, they can do a re-name to the extension that you're polling for. That could also speed up things.
    Regards, Trevor
    Edited by: Trevor Naidoo on Oct 8, 2009 9:38 AM

  • Using "Send Update" from the address book file menu.

    I plan to use the "Send Update" from the File menu in Address Book to notify a large group I've created of my upcoming change of address. If a person on my list of people to to receive the update message has more than one email address, to which email address does Address Book send the message? All email address' of each person?
    Also, I assume, from the email message window created when sending an update, recipients will see only the name of the group I created instead of all of the email addresses of all the people to which the update was sent. Have I assumed correctly?

    How did you move your Thunderbird data from its default position?
    If you had simply shifted your entire profile, the address book files would have moved too, so I suspect you've used the dangerous and inadvisable "Local Directory" option in Account Settinhgs to relocate specific mailstore files. :-(
    I don't know of any way to set the path for address books. They are, it seems, required by design to reside in the user profile folder.
    I don't like to advise use of the Local Directory settings, since doing so detaches message stores from your profile and makes profile management and maintenance a whole lot more difficult. Automated tools such as Mozbackup won't know to look outside the regular profile to safeguard your messages. All the published advice about profile management assumes you use the default locations which are within the profile. The Local Directory setting should, IMHO, be hidden inside the about:config editor for use only by power users.

  • FTP: Want to check if the file is completely being written in the server or

    Hi,
    I am very much new to this FTP, I am using the apache API (commons-net.jar) in my ftp client.
    I have a problem here, I want to find out whether the remote file (in the server) is completely written or not. Is there anyway in which the mode (writing, written, etc ) of the file can be determined?
    Thanks in advance for any comments
    Regards
    Raaghu.K

    There is no good, direct way to do so. The two strategies I have seen to accomplish what you are looking for are:
    1. Create a 'done' file (naming convention can be whatever you like). Write the main file first, then write the done file. Your polling program should look for the existence of the done file. That will indicate the main file has finished transmission.
    2. Create a header file (naming convention can be whatever you like). Include a count (line count, record count, byte count, or whatever) in the header file. When reading the detail file, verify that the count is correct.
    - Saish

Maybe you are looking for

  • Can't stop music from syncing to wrong i-Pod.

    Hi, Just bought a Nano for my wife and I have had a Classic for several years. We both use the same computer. I have previously downloaded i-Tunes and currently have tons of music there. Problem is, whenever I connect my wife's i-Pod to i-Tunes it im

  • Embedding Audio Clips in PDF Document

    Hello, I would like to be able to embed very short audio clips/files in a document, with a "play" button/icon that allows users to click on it and here a brief text excerpt.  Is this possible with Acrobat?  Would I have to use Flash to accomplish thi

  • Configure SMTP server profile on CRM 2015 online

    Hi, I am trying to get the CRM mail router to work with CRM 2015 online. I use smtp.org.com as the address, but I get this error: ' Unsupported Email server. The specified email server location isn't supported by server side synchronization. Specify

  • Internet Connect freezes up; status "disconnecting" never ends.

    Hello, I use Earthlink dial-up service. Lately, when I try to connect, often the status will jump from "connecting" to "disconnecting". When in that status, it stays there; I can't re-connect. Logging off does not help. I have to restart. Any ideas?

  • Best way to place lots of images into one

    Hello, I have made a Javascript script that loops between 20.000+ images and puts them into a main image. Code is: var sampleDocToOpen = File('~/a/'+(l+startF)+'/'+(i+start)+'.png') open (sampleDocToOpen) app.activeDocument.selection.selectAll() app.