1

my program has the following code,

BufferedWriter bufWriter = new BufferedWriter(new FileWriter(new File("xyz.dat"),true));
                        bufWriter.write(nameField+"/"+ageField+"/"+genderField+"\n");
                        bufWriter.flush();

Which creates a file.. Sample Format of data stored in file..

Name1/Age1/Gender1                            // for user1
Name2/Age2/Gender2                            // for user2
.
.
.
NameN/AgeN/GenderN                            //for userN

Suppose I need to change the age of the user5 then how can i do it? I can navigate to the 5th user and I can get the data through the split("/",3);method but how to make changes for that particular user ? I am really very confused here.

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46
  • 1
    WIth the BufferedWriter approach you will have to read whole file, change the record and save it back to the disk. You can use RandomAccessFile to seek to particular record (line), read and update it and save the file- but, implementing this will not be trivial, you will have to manage record boundaries etc. Other option is to keep 1 file per user data and save it with index of user name e.g. user5.data. Then you can just read user5.data and update it. – Bimalesh Jha Jul 03 '13 at 04:31

2 Answers2

1

Youhave to make the serilizable object of each record and then acess it and update it as below,

import java.io.*;

public class phoneBook {
private ObjectOutputStream output;
private ObjectInputStream input;
File fileName = new File("d:\\java\\data\\phone.dat");

public static void main(String[] args) {
   phoneBook pb = new phoneBook();
   pb.writeFile(); // open, write and close the file
   pb.readFile(); // open, read and close the file
}

public void writeFile() {

   // I could have put this into an array which would have told me how many
   // records i have, it could then have be used in the readFile method below
   // but lets keep things very simple
   Record r1 = new Record("Paul Valle", "0207-568-789");
   Record r2 = new Record("Lorraine Valle", "0207-345-356");
   Record r3 = new Record("Dominic Valle", "0207-765-693");
   Record r4 = new Record("Jessica Valle", "0207-789-876");

   try {
      // Open a file handle for writing
      output = new ObjectOutputStream( new FileOutputStream( fileName));

      // Write some data to the file it could throw
      // InvalidClassException or NotSerializableException exceptions
      output.writeObject( r1 );
      output.writeObject( r2 );
      output.writeObject( r3 );
      output.writeObject( r4 );

      // Flush the ObjectOutputStream. This will write any buffered
      // output bytes and flush through to the FileOutputStream
      output.flush();

      // Close the file
      output.close();
   } catch (InvalidClassException icex) {
      System.out.println("Invalid Class");
   } catch (NotSerializableException nsex) {
      System.out.println("Object is not serializable");
   } catch (IOException e) {
      System.out.println("Problems either flushing or closing file");
   }
}

public void readFile() {
   Record r; // this object will hold the records when retrieved from the file

   try {
      // Open the file handle for reading
      input = new ObjectInputStream( new FileInputStream(fileName));

      // I know i have 4 records so lets read them, this is where i could have used the array
      // by using the length of the array i would have know how many records i have.
      for (int i = 0; i < 4; i++ ) {
         // Here we implicity cast the retrieved Object
         r = ( Record ) input.readObject();
         if (r.getName() == 'YOURMATCHINGNAME')
          {
               r.setName("NEWNAME");
               r.setPhone("NEWPHONENUMBER");  
               try {
                      // Open a file handle for writing
                      output = new ObjectOutputStream( new FileOutputStream( fileName));

                     // Write same data to the file it could throw
                     // InvalidClassException or NotSerializableException exceptions
                     output.writeObject( r );

                     // Flush the ObjectOutputStream. This will write any buffered
                    // output bytes and flush through to the FileOutputStream
                    output.flush();

                    // Close the file
                   output.close();
                   } catch (InvalidClassException icex) {
                       System.out.println("Invalid Class");
                   } catch (NotSerializableException nsex) {
                      System.out.println("Object is not serializable");
                   } catch (IOException e) {
                      System.out.println("Problems either flushing or closing file");
                  }  
                 finally{
                    break;
                  }  
          }  

      }

      // Close the file
      input.close();

   } catch (EOFException eofex) {
      System.out.println("No more records to read");
   } catch (ClassNotFoundException cnfex) {
      System.out.println("Unable to create object - class not found");
   } catch (IOException e ) {
      System.out.println("Unable to close file");
   }
 }
}

 // Serialization involves saving the current state of an object to a stream,
 // and restoring an equivalent object from that stream.
class Record implements Serializable {

private String name;
private String phone;

// Constructor
public Record() { this ("", ""); }

// Overloaded Constructor
public Record(String n, String p) {
   name = n;
   phone = p;
}

// The get and set methods
 public void setName(String n) { name = n; }

 public void setPhone(String p) { phone = p; }

 public String getName() { return name; }

 public String getPhone() { return phone; }
}

This will do.Let me know if any problem.

Mahesh
  • 8,694
  • 2
  • 32
  • 53
1

1) Solution for a short file (which fits in memory) with Java 7

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
String line5 = replaceAge(lines.get(4), newAge);
lines.set(4, line5);
Path tmp = Files.createTempFile(prefix, suffix, attrs);
Files.write(path, lines)
Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);

2) For a big file

    Path tmp = Files.createTempFile(prefix, suffix, attrs);
    try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
            BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
        String line;
        for (int i = 1; (line = br.readLine()) != null; i++) {
            if (i == 5) {
                line = replaceAge(line, newAge);
            }
            bw.write(line);
            bw.newLine();
        }
    }
    Files.move(tmp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275