RandomAccessFile

This class does not have a writeObject or readObject method like the ObjectOutputStream and the ObjectInputStream
How am I supposed to write and read objects using random access files? Is there anyway besides just manually writing every primitive data to the file and then reading it again the same way?
I did something insane like this:
     try
               RandomAccessFile file;
               file = new RandomAccessFile(fileName, "r");
               ntot = "";
               for(int i = 0; i < 10; i ++)
                    //temp = file.readChar();
                    //data[count++] = temp;
                    //record = new Person("Person number" + i , i);
                    record = new Person();
                    record.read(file);
                    n1 = record.getName();
                    n2 = record.getAge();
                    ntot += n1 + n2 + "\n";
          catch(IOException ioException)
               JOptionPane.showMessageDialog(null, "no file available");
               //     stuff = new String(data).replace('\0' , ' ');
          }The person object looks like this:
class Person
     String name;
     int age;
     public Person()
          name = "";
          age = 0;
     public Person(String name1, int age1) throws IOException
          name = name1;
          age = age1;
     public String getName(){return name;}
     public int getAge(){return age;}
     public void write(RandomAccessFile file) throws IOException
          //StringBuffer buffer = null;
          //buffer = name;
          file.writeChars(name);
          file.writeInt(age);
     public void read(RandomAccessFile file) throws IOException
          char temp;
          int counter = 0;
          do
               temp = file.readChar();
               name += name + temp;
               counter++;
          }while(counter != 3);
          age = file.readInt();
               JOptionPane.showMessageDialog(null, ""+ counter);
     }But it doesn't work well...I do get some data, but It gives me weird characters and stuff.
How can we use random access files by just manipulating objects?

so you're saying that the only way to manipulate
objects in files is by using suquential files?
What am I supposed to do then? use JDBC?Either that or use a data model you load completely from a file, manipulate "in memory", and store again when you done.
Byte-wise manipulation is exactly what you need to do otherwise, but serialized objects aren't supposed to be manipulated - it's possible, but quite difficult.

Similar Messages

  • Going to a certain line in a RandomAccessFile?

    Hi, this doesn't seem to belong anywhere else, since Java doesn't have a forum on I/O. This is pretty simple, but is there any way to go to a certain line in a RandomAccessFile (such as a text file)? seek() doesn't work, it only starts from the character on a line. Is there a way, or should I be using a different kind of I/O medium?
    Frumple

    well, i would recommend using a random access file and the seek() method... what are you trying to do? like, are you trying to search through the file?
    if youre trying to search somehow, then i would write method thatll use a binary search on the file. but, it wouldnt actually store the file contents in a vector or anything, it would use the file.length() property to get the length, and then divide that in half, etc.... now, when you divide it in half, you wont always get to the first position of the line, so you would have to increment/decrement the seek position, until you reach the end of the line... this sounds difficult and it kinda sounds like itll slow down the program.. but, actually i just wrote a method that does this and its AMAZINGLY fast. extremely fast...
    good luck. talk to ya later,
    Steven Berardi
    ---------------------

  • 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);
    }

  • Inserting strings in a RandomAccessFile at a particular location

    I wrote a java program to read and display the contents of RAF. It is working. Actually,I need to read a file and search for a string in it and if the string equals certain value, then i need to insert a line in the file at that location.
    My problem is I am not able to insert any string in the RandomAccessFile(RAF) at a particular location, it always overwrites the already present string.
    I have a file called SOE_Arrays2.js which needs to be read and its content has to be modified. I am searching for a string like "os = [" in it and inserting another line like "["64w","64-bit Windows"]," at that location.
    the file looks like this:
    os1 = [
    ["win","Windows"],
    ["unx","UNIX"],
    ["mvs","MVS"]
    os2 = [
    ["alp","Alpha VMS"],
    ["lnx","Linux"]
    var letter = [
    ["new","New"],
    ["addon","Add-on"],
    ["lsf","LSF"],
    ["renew","Renewal"]
    The java program i wrote is here:
    import java.io.*;
    public class RAFtest
         public void writeTo()
              try
         String f = "C:\\webapps\\oncall\\soe\\SOE_Arrays2.js";
         File arrayfile = new File(f);
         RandomAccessFile raf = new RandomAccessFile(arrayfile, "rw");
         String s="",ss="";
         int i,j = 0,len;
         long fp;
    while((s = raf.readLine()) != null)
              //System.out.println(s);
              int ptr = 0;
              ptr = s.indexOf("os2 = [");
              if(ptr != -1)
                   System.out.println(s);
                   System.out.println("The OS array is here:");
                   ss = s;
                   raf.writeBytes("\r\t");
                   fp = raf.getFilePointer();
                   raf.seek(fp-4);
              raf.writeBytes("[\"64w\",\"64-bit Windows\"],\r");
                   break;
         raf.close();     
         catch(Exception e){e.printStackTrace(System.out);}      
         public static void main(String args[])
              RAFtest e = new RAFtest();
              e.writeTo();
    After executing the code SOE_Arrays2.js looks like this:
    os1 = [
    ["win","Windows"],
    ["unx","UNIX"],
    ["mvs","MVS"]
    os2 = [["64w","64-bit Windows"],
    lnx","Linux"]
    var letter = [
    ["new","New"],
    ["addon","Add-on"],
    ["lsf","LSF"],
    ["renew","Renewal"]
    you can see that RAF overwrites to the file at that particular location( after the line "os2 = [ ". What i need is to insert the text at a particular location, Is there a way to do this?
    I tried to insert carriage return, etc and move the file ptr back a little and write, whatever it is, RAF overwrites it, is there a way to insert instead of overwrite?
    Basically I want to get some string from the user from a web page and insert that string in my SOE_Arrays2.js file at a particular location depending on certain conditions.
    Is there another way of doing this instead of RAF?
    Please let me know how to do this.
    Thanks,
    Priyha.

    Hi DrClap,
    Thanks for the clarification. Everything works except the renameTo() . I am trying to rename the arrayfile2 to arrayfile1 , but the rename always return false. I am not sure why rename is not successful.
    I checked for the permissions of the file, full permission is there. I closed the files before renaming.
    Here's the code.
    import java.io.*;
    public class RAFtest
    public void writeTo()
    try
    String f1 = "C:\\JAVA\\SOE_Arrays2.js";
    String f2 = "C:\\JAVA\\SOE_Arrays3.js";
    File arrayfile1 = new File(f1);
    File arrayfile2 = new File(f2);
    RandomAccessFile raf1 = new RandomAccessFile(arrayfile1, "rw");
    RandomAccessFile raf2 = new RandomAccessFile(arrayfile2, "rw");
    long fp1=0,fp2=0; // file pointers
    String s="",ss="";
    int i,j = 0,len;
    boolean b= false;
    raf2.seek(0);
    while((s = raf1.readLine()) != null)
    int ptr = 0;
    raf2.writeBytes(s);
    ptr = s.indexOf("var OS9.1_sol = [");
         if(ptr != -1)
              System.out.println(s);
              System.out.println("The OS array is here:");
              ss = s;
              fp1 = raf1.getFilePointer();
              raf2.writeBytes("[\"64w\",\"64-bit Windows\"],");
              fp2 = raf2.getFilePointer();
              break;
    raf1.seek(fp1);
    while((s = raf1.readLine()) != null)
         raf2.writeBytes(s);               
    raf1.close();
    raf2.close();
    if(arrayfile2.exists()) System.out.println("file2 exists!");
    try{
    b = arrayfile2.renameTo(arrayfile1); //rename the file, why does it return false?
    }catch(SecurityException se){se.printStackTrace(System.out);}
    catch(NullPointerException ne){ne.printStackTrace(System.out);}
    System.out.println("b: "+b);
    catch(Exception e){e.printStackTrace(System.out);}
    public static void main(String args[])
    RAFtest e = new RAFtest();
    e.writeTo();
    here is the SOE_Arrays2.js
    var OS9.1 = [
    ["win","Windows"],
    ["unx","UNIX"],
    ["mvs","MVS"]
    var OS9.1_sol = [
    ["alp","Alpha VMS"],
    ["lnx","Linux"]
    var letter = [
    ["new","New"],
    ["addon","Add-on"],
    ["lsf","LSF"],
    ["renew","Renewal"]
    Please let me know whats wrong with the above code. I have no clue why renameTo returns false.
    Thanks,
    Priyha

  • How to use text files in RandomAccessFile both are in same Jar file

    when double click the executable jar file the class file contains the RandomAccessFile ,it will not take the text files,both the files are in jar file

    I used this:
    Scanner fileScan = new Scanner (new file
    ("Words.txt"));
    but when I make a jar file, it doesnt find the txt
    file inside a jar,
    do I need to specify path or something?I have already told you that you shouldn't use new File(..) you should use getResourceAsStream(String name) to get an InputStream to the file.
    Kaj

  • Delete the specified character in a text file using RandomAccessFile

    Hi All,
    I have an invalid XML file which contains Return characters at the end of each line. I need to delete these return characters so the file becomes valid.
    Does anybody have any idea how this could be done using RandomAccessFile?
    I found joop_eggen's posting in this forum, modified it just a little and wanted to use it, but since the replacement character is "" (blank) it does not do what I need to.
    The XML file looks like this:
    <?xml version="1.0"?>
    <EPMSObject>
    <EPMSRecord><facilityname>KT0</facilityname><date_time>2007-06-01T00:00:00</date_time><devicetype>RPP</devicetype><devicename>RPP1A1_001.BCMF</devicename><meter>BCMF</meter><ckt_01_current>4.136000000000000e+000</ckt_01_current><ckt_02_current>0.000000000000000e+000</ckt_02_current><ckt_03_current>5.521000000000000e+000</ckt_03_current><ckt_04_current>0.000000000000000e+000</ckt_04_current><ckt_05_current>5.880000000000000e+000</ckt_05_current><ckt_06_current>0.000000000000000e+000</ckt_06_current><ckt_07_current>4.086000000000000e+000</ckt_07_current><ckt_08_current>0.000000000000000e+000</ckt_08_current><ckt_09_current>4.994000000000000e+000</ckt_09_current><ckt_10_current>0.000000000000000e+000</ckt_10_current><ckt_11_current>4.374000000000000e+000</ckt_11_current><ckt_12_current>0.000000000000000e+000</ckt_12_current><ckt_13_current>4.314000000000000e+000</ckt_13_current><ckt_14_current>0.000000000000000e+000</ckt_14_current><ckt_15_current>4.112000000000000e+000</ckt_15_current><ckt_16_current>0.000000000000000e+000</ckt_16_current><ckt_17_current>4.287000000000000e+000</ckt_17_current><ckt_18_current>0.000000000000000e+000</ckt_18_current><ckt_19_current>4.254000000000000e+000</ckt_19_current><ckt_20_current>0.000000000000000e+000</ckt_20_current><ckt_21_current>3.970000000000000e+000</ckt_21_current><ckt_22_current>0.000000000000000e+000</ckt_22_current><ckt_23_current>5.640000000000000e+000</ckt_23_current><ckt_24_current>0.000000000000000e+000</ckt_24_current><ckt_25_current>7.123000000000000e+000</ckt_25_current><ckt_26_current>0.000000000000000e+000</ckt_26_current><ckt_27_current>5.118000000000000e+000</ckt_27_current><ckt_28_current>0.000000000000000e+000</ckt_28_current><ckt_29_current>6.094000000000000e+000</ckt_29_current><ckt_30_current>0.000000000000000e+000</ckt_30_current><ckt_31_current>0.000000000000000e+000</ckt_31_current><ckt_32_current>0.000000000000000e+000</ckt_32_current><ckt_33_current>0.000000000000000e+000</ckt_33_current><ckt_34_current>0.000000000000000e+000</ckt_
    34_current><ckt_35_current>0.000000000000000e+000</ckt_35_current><ckt_36_current>0.000000000000000e+000</ckt_36_current><ckt_37_current>0.000000000000000e+000</ckt_37_current><ckt_38_current>0.000000000000000e+000</ckt_38_current><ckt_39_current>0.000000000000000e+000</ckt_39_current><ckt_40_current>0.000000000000000e+000</ckt_40_current><ckt_41_current>0.000000000000000e+000</ckt_41_current><ckt_42_current>0.000000000000000e+000</ckt_42_current></EPMSRecord>
    </EPMSObject>
    Here is joop_eggen's code:
    import java.io.*;
    import java.nio.*;
    import java.nio.channels.*;
    public class Patch {
      private static byte[] sought;
      private static byte[] replacement;
      private static boolean matches(MappedByteBuffer bb, int pos) {
        for (int j = 0; j < sought.length; ++j)
          if (sought[j] != bb.get(pos + j))
            return false;
        return true;
      private static void replace(MappedByteBuffer bb, int pos) {
        for (int j = 0; j < sought.length; ++j)
          byte b = (j < replacement.length)? replacement[j] : (byte)' ';
          bb.put(pos + j, b);
      private static void searchAndReplace(MappedByteBuffer bb, int sz) {
        int replacementsCount = 0;
        for (int pos = 0; pos <= sz - sought.length; ++pos)
          if (matches(bb, pos)) {
            replace(bb, pos);
            pos += sought.length - 1;
            ++replacementsCount;
        System.out.println("" + replacementsCount + " replacements done.");
        // Search for occurrences of the input pattern in the given file
        private static void patch(File f) throws IOException {
        // Open the file and then get a channel from the stream
        RandomAccessFile raf = new RandomAccessFile(f, "rw"); // "rws", "rwd"
        FileChannel fc = raf.getChannel();
        // Get the file's size and then map it into memory
        int sz = (int)fc.size();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0, sz);
        searchAndReplace(bb, sz);
        bb.force(); // Write back to file, like "flush()"
        // Close the channel and the stream
        raf.close();
        public static void main(String[] args) {
        String E_O_L;
        E_O_L = System.getProperty( "line.separator" );
        if (args.length == 0)
          args = new String[] { E_O_L, "", "C:\\GTI\\EPMSRecords.xml" };
        if (args.length < 3) {
          System.err.println("Usage: java Patch sought replacement file...");
          return;
        sought = args[0].getBytes();
        replacement = args[1].getBytes();
        //if (sought.length != replacement.length) {
          // Better build-in some support for padding with blanks.
          //System.err.println("Usage: sought (" + args[0] + ") and replacement (" + args[1] + ") must have same length");
          //return;
        for (int i = 2; i < args.length; i++) {
          File f = new File(args);
    try {
    patch(f);
    } catch (IOException x) {
    System.err.println(f + ": " + x);
    Thank you,
    Sinan Topuz

    Thank you all.
    Here is what I have right now and it works very well. It takes a couple of seconds to generate the second file and that satisfies me. I took the code sabre150 posted in this forum and changed it just a little bit, so thanks to him.
    I hope this helps someone.
    Sinan
    import java.io.*;
    public class SearchReplace{
        public static void main(String[] args){
            if(null == args || args.length < 2) {
               System.err.println("\nUsage: java <inputFileFullPath> <OutputFileFullPath> \nExample: java C:\\GTI\\Epmsrecord.xml C:\\GTI\\EpmsrecordNEW.xml");
               System.exit(1);
            Reader reader = null;
            Writer writer = null;
            try{
                char cr;
                char lf;
                char sp;
                int  indx;
                cr = '\r';
                lf = '\n';
                sp = ' ';
                indx = 0;
                reader = new FileReader(args[0]);
                writer = new FileWriter(args[1]);
                for (int ch = ' '; (ch = reader.read()) != -1;){
                    indx++;
                    if ( indx > 15 ) {      // Skip the first space character in <?xml version="1.0"?> otherwise the file becomes invaild!
                        if (ch != cr && ch != lf ) {
                            writer.write(ch);
                    }else{
                        writer.write(ch);
                System.out.println("\nFile " + args[1] + " has been successfully created.");
            }catch(FileNotFoundException fnfe){
                System.out.println("\nError : File " + args[0] + " not found. Please make sure it exists and you have rights to access to it.");
            }catch (IOException e) {
                System.err.println("Caught IOException: " +  e.getMessage());
            }finally {
                try {
                    if ( reader!=null ) {
                        reader.close();
                    if ( writer!=null ) {
                        writer.close();
                }catch (IOException e){
                    System.err.println("I/O error occured while trying to close the files.");
    }

  • The concurrent io problem when using RandomAccessFile

    Hi:
    In my application,I have to export the tomcat log(the log file like "localhost_access_log.2010-10-13") to database and the do some analisis.
    My way:
    start to export log at 00:05:00 every day,at this moment just read the log whose date before yesterday.
    For example,at 2010-12-12 00:05:00,the log of 2010-12-11... 2010-12-01 ..2010-11-12...(just check the nearest 30 days).
    All of these data are put into one table named "log".
    If log of one day is exported successfully,insert one record to another table named 'logrecord'.
    //main code fragment:
         public void start() {
              //start the push export work once the server startup.
              run();
              //start the schedule work
              new ScheduledThreadPoolExecutor(5).scheduleAtFixedRate(this, getStartTime(), 24 * 3600,
                        TimeUnit.SECONDS);
         //return the left time(from now to 00:05:00 of tomorrow)
         private long getStartTime() {
              Date d = new Date();
              long t = (DateUtil.getNextDayAtMiddleTime(d).getTime() - d.getTime()) / 1000 + 300;
              return t;
         @Override
         public void run() {
              Date days[] = DateUtil.getSeveralDayRangeByTime(30); //just the nearest 30 days.
              for (Date d : days) {
                   if (exist(d)) {
                        continue;
                   exportLogByDate(d);
    It works for now expect we can not anlyzer data of today.
    However we need it now.
    As far as I thought,I want to create a new table which owns the same structure of the former table "log" used to hold the log of "today" only.
    At 00:05:00 of every day,after the normal log exporting(export the nearest 30 days'log but today),export the log of today.
    It sounds easy,read the content,parser,filter,insert,just like what I did.
    But,the tomcat log file is saved by day.So in my normal log exporting,the log file(nearest 30 days) are not be used by tomcat,I can open/close it as I like.
    However if I tried to read the log of today,since the log file maybe used by tomcat for inserting log.
    I prefer to use the RandomAccessFile to read the log of today:
    But I am coufused by the concurrent io problem:what is going on if I am reading a line while tomcat is writing the line?
    Here is my test exmaple:
    package com.test;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import org.junit.BeforeClass;
    import org.junit.Test;
    public class TestMain {
         private static File          file;
         private static long          pos; //record the position of last time
         private static Thread     writterThread;
         @BeforeClass
         public static void init() {
              file = new File("D:/random.txt");
              // build the thread for simulating the tomcat write log
              writterThread = new Thread(new Runnable() {
                   @Override
                   public void run() {
                        FileWriter fw;
                        try {
                             fw = new FileWriter(file);
                             BufferedWriter bw = new BufferedWriter(fw);
                             int i = 0;
                             while (true) {
                                  i++;
                                  bw.append(i + " added to line...");
                                  bw.append("\r\n");
                                  bw.flush();
                                  Thread.sleep(5000);
                        } catch (IOException e) {
                             e.printStackTrace();
                        } catch (InterruptedException e) {
                             e.printStackTrace();
         @Test
         public void testRandomRead() throws IOException, InterruptedException {
              writterThread.start();
              try {
                   RandomAccessFile raf = new RandomAccessFile(file, "r");
                   String line;
                   while ((line = raf.readLine()) != null) {
                        System.out.println(line);
                   pos = raf.getFilePointer();
                   raf.close();
                   // read the file by 30 seconds within 2 min,just for test)
                   for (long m = 0; m < 1000 * 60 * 2; m += 30000) {
                        raf = new RandomAccessFile(file, "r");
                        raf.seek(pos);
                        while ((line = raf.readLine()) != null) {
                             System.out.println(line);
                        pos = raf.getFilePointer();
                        raf.close();
                        Thread.sleep(30000);
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
    The normal output is something like:
    1 added to line...
    2 added to line...
    3 added to line...
    4 added to line...
    5 added to line...
    However I always get the following output:
    1
    added to line...
    2 added to line...
    3 added to line...
    4 added to line...
    5
    added to line...
    That's to say,the RandomAccessFile is reading the line which has not been completed by tomcat.
    So,I have two questions now:
    1) How about my normal log exporting? Is there anything can be improved?
    2) How to slove the concurrent io problem when export log of today?

    Peter Lawrey wrote:
    You can;
    - check the length to see if it has grown since the last time it was written to. If it has shrunk, start from the start of the file.
    - if longer, open the file from the last point read.
    - read the text up to the last newline in the file. (might be no new lines)
    - close the file and remember where you were up to. (the start of the last incomplete line.
    - wait a bit and repeat.But how to decide if one line is completed?
    Also,how about if the randomaccessfile can not stop?
    For example,start the work at 02:00,it read the tomcat log file line by line and export them to db,and during this time,the tomcat keep writing log to the same file(user request the server all the time), and then the randomaccessfile will keeping reading accordingly,when it is 03:00,the last task is not completed,but a new task should start,how to control this?

  • How to find EOF in RandomAccessFile

    hi all,
    How can we find the end of file while using RandomAccessFile. Can some one help me out on this...
    Thanks in advance...

    CeciNEstPasUnProgrammeur wrote:
    I'm not sure what you want - asking for length()-1? What exactly are you looking for? Java handles EOF markers transparently, you won't come across one.Well, "getFilePointer" returns the offset at which the next write would start, so "getFilePointer" >= "length" will mean you are at (at least the current) EOF.

  • Urgent!! RandomAccessFile help!!! please!!!

    hi.
    i'm trying to write records (objects) to a RAF. Each record consist of 1 String and 4 int's. And because i have to read some records randommly i'm using RandomAccessFile.
    the following code show the structure of a record and the methods used to manipulate the record's data:
    import java.io.*;
    public class RegistroSalon
         String clave;
         int posicion, capacidad, modulo, edificio;
         public void read (RandomAccessFile archivo) throws IOException
              byte arregloClave[] = new byte[5];
              posicion = archivo.readInt();
              archivo.readFully(arregloClave);
              clave = new String (arregloClave);
              capacidad = archivo.readInt();
              modulo        = archivo.readInt();
              edificio  = archivo.readInt();
         public void write (RandomAccessFile archivo) throws IOException
              byte arregloClave[] = new byte[5];
              if (clave != null)
                   arregloClave = clave.getBytes();
              archivo.writeInt(posicion);
              archivo.write(arregloClave);
              archivo.writeInt(capacidad);
              archivo.writeInt(modulo);
              archivo.writeInt(edificio);
         public int size () { return 21; }
    }the next class creates a new file (which is in the same path of my *.java) with blank records:
    import java.io.*;
    public class CrearArchivoSalon
         private RegistroSalon registro;
         RandomAccessFile archivo;
         public CrearArchivoSalon ()
              registro = new RegistroSalon ();
              try
                   archivo = new RandomAccessFile ("salon.txt", "rw");
              catch (IOException e)
                   System.err.println("Error al abrir el archivo salon.txt " + e.toString());
                   System.exit(1);
         public void crear ()
              try
                   for (int i = 0; i < 62; i++)
                        archivo.seek(i * registro.size());
                        registro.write(archivo);
              catch (IOException e)
                   System.err.println("Error al escribir en el archivo salon.txt " + e.toString());
                   System.exit(1);
         public static void main (String args[])
              CrearArchivoSalon salones = new CrearArchivoSalon ();
              salones.crear();
    }the next code is a part of my class that writes records to the RAF:
         public void addRecord ()
              int posicion = 0;
              try
                   try
                        posicion = (new Integer (campoPos.getText())).intValue();
                        registro.posicion  = posicion;
                        registro.clave        = campoClave.getText();
                        registro.capacidad = (new Integer (campoEst.getText())).intValue();
                        registro.modulo    = (new Integer (campoMod.getText())).intValue();
                        registro.edificio  = (new Integer (campoEdif.getText())).intValue();
                        archivo.seek((long) posicion * registro.size());
                        registro.write(archivo);
                   catch (NumberFormatException e) { }
                   campoPos.setText("");
                   campoClave.setText("");
                   campoEst.setText("");
                   campoMod.setText("");
                   campoEdif.setText("");
              catch (IOException e1)
                   System.err.println("Error al escribir en salon.txt " + e1.toString());
                   System.exit(1);
         }for last, the next code is part of my class that reads form the RAF:
         public void readRecord ()
              try
                   do { registro.read(archivo); }
                   while (archivo.getFilePointer() < archivo.length() && registro.posicion == 0);
              catch (IOException e) { masRegistros = false; }
              if (registro.posicion != -1)
                   campoPos.setText(String.valueOf(registro.posicion));
                   campoClave.setText(registro.clave);
                   campoEst.setText(String.valueOf(registro.capacidad));
                   campoMod.setText(String.valueOf(registro.modulo));
                   campoEdif.setText(String.valueOf(registro.edificio));
         }i have used the same classes in a previuos program, of course, with different record's fields. It worked just fine. But now i do not know why but it returns me different values for the originals. For example, if the written input is:
    registro.posicion = 1
    registro.clave = 2103
    registro.capacidad = 44
    registro.modulo = 100
    registro.edificio = 2
    the output is (when i read the RAF):
    registro.posicion = 1
    registro.clave = 2103
    registro.capacidad = 11264
    registro.modulo = 25600
    registro.edificio = 512
    can anyone suggest why my records are not being correctly read from the file?
    regards and thanks in advance.

    Sudha!! Thank you for your attention. I guess you have already discovered I ain't an anglospeaker. But I'm going to do my best.
    I have 2 files.
    In one of them I write/read records which have:
    1 String and 6 int's. These kind of record is called RegistroCurso, defined here:
    import java.io.*;
    public class RegistroCurso
         String clave;
         int posicion, capacidad, modulo, horaInicio, horaFin, edificio;
         public void read (RandomAccessFile archivo) throws IOException
              byte arregloClave[] = new byte[7];
              posicion = archivo.readInt();
              archivo.readFully(arregloClave);
              clave = new String (arregloClave);
              capacidad = archivo.readInt();
              modulo        = archivo.readInt();
              horaInicio= archivo.readInt();
              horaFin   = archivo.readInt();
              edificio  = archivo.readInt();
         public void write (RandomAccessFile archivo) throws IOException
              byte arregloClave[] = new byte[7];
              if (clave != null)
                   arregloClave = clave.getBytes();
              archivo.writeInt(posicion);
              archivo.write(arregloClave);
              archivo.writeInt(capacidad);
              archivo.writeInt(modulo);
              archivo.writeInt(horaInicio);
              archivo.writeInt(horaFin);
              archivo.writeInt(edificio);
         public int size () { return 31; }
    }Like you can see, the basic difference between the RegistroCurso's records and RegistroSalon's (defined earlier in this page) records are the number of attributes or fields and the value of the method size ().
    When I wrote/read to the file of the records type RegistroCurso there was no problem.
    But, when I try to read the content of the file that stores records type RegistroSalon don't appear the original values.
    Now, my question is: what is happening?
    I mean, why it worked for a kind of record and do not work for another kind? The difference between RegistroCurso records and RegistroSalon records is just 10 bytes!!
    Thanks, again.
    Omar.

  • RandomAccessFile and BufferedImage

    Is it possible to put lots of BufferedImage inside a File Using RandomAccessFile?
    If yes, how can i do this? How will be the file, and how to read the file?
    thanks... This is urgent! Please!

    Some formats, like jpeg and especially tiff allow for a series of images in a single file,
    but I don't think that's the case with png. Must your file format be png? If your source images
    are pngs it doesn't necessarily imply that you can't write them out in a different format,
    although there are always potential issues there (transparency, etc...).
    For example, here is a demo that reads four seperate images, writes them to a single file
    and reads them back from that file to display the result.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class IOExample {
        public static void main(String[] args) throws IOException {
            String urlPrefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
            String urlSuffix = "_800x600.jpg";
            int SIZE = 4;
            BufferedImage[] images = new BufferedImage[SIZE];
            for(int i=1; i<=SIZE; ++i)
                images[i-1] = ImageIO.read(new URL(urlPrefix + i + urlSuffix));
            File file = new File("test.jpeg");
            file.delete();
            int count = writeImages(images, file);
            if (count < SIZE)
                throw new IOException("Only " + count + " images written");
            images = null;
            images = readImages(file);
            if (images.length < SIZE)
                throw new IOException("Only " + images.length + " images read");
            display(images);
        public static void display(BufferedImage[] images) {
            JFrame f = new JFrame("IOExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel(new GridLayout(0,1));
            for(int j=0; j<images.length; ++j) {
                JLabel label = new JLabel(new ImageIcon(images[j]));
                label.setBorder(BorderFactory.createEtchedBorder());
                p.add(label);
            f.getContentPane().add(new JScrollPane(p));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //suffix is "jpeg", "gif", "png", etc... according to your service providers
        public static ImageWriter getWriter(String suffix) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
            if (!writers.hasNext())
                throw new IOException("no writers for suffix " + suffix);
            return (ImageWriter) writers.next();
        public static ImageReader getReader(String suffix) throws IOException {
            Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
            if (!readers.hasNext())
                throw new IOException("no reader for suffix " + suffix);
            return (ImageReader) readers.next();
        public static int writeImages(BufferedImage[] sources, File destination) throws IOException {
            if (sources.length == 0) {
                System.out.println("Sources is empty!");
                return 0;
            } else {
                ImageWriter writer = getWriter(getSuffix(destination));
                ImageOutputStream out = ImageIO.createImageOutputStream(destination);
                writer.setOutput(out);
                System.out.println("can write sequence = " + writer.canWriteSequence());
                writer.prepareWriteSequence(null);
                for(int i=0; i<sources.length; ++i)
                    writer.writeToSequence(new IIOImage(sources, null, null), null);
    writer.endWriteSequence();
    return sources.length;
    public static BufferedImage[] readImages(File source) throws IOException {
    ImageReader reader = getReader(getSuffix(source));
    ImageInputStream in = ImageIO.createImageInputStream(source);
    reader.setInput(in);
    ArrayList images = new ArrayList();
    GraphicsConfiguration gc = getDefaultConfiguration();
    try {
    for(int j=0; true; ++j)
    images.add(toCompatibleImage(reader.read(j), gc));
    } catch(IndexOutOfBoundsException e) {
    return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    public static String getSuffix(File file) throws IOException {
    String filename = file.getName();
    int index = filename.lastIndexOf('.');
    if (index == -1)
    throw new IOException("No suffix given for file " + file);
    return filename.substring(1+index);
    //make compatible with gc for faster rendering
    public static BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc) {
    int w = image.getWidth(), h = image.getHeight();
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(w, h, transparency);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
    public static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();
    Another option that always works is to use zip format on your file, and put whatever you want
    into it. The classes in package java.util.zip make this straightforward.

  • Beginner Question - RandomAccessFiles

    Hello!
    I was working on a project... for school (Yes, it's homework :P) and I am supposed to make a program that uses random access files. I've done it before but I've gotten stuck on this one. An error occurs that I am not able to correct - because it has never happened to me before?!? Thanks for taking the time to read this. :)
    ERROR:
    java.lang.NullPointerException
    at Arecord.fillspace(Arecord.java:123)
    at Arecord.write(Arecord.java:104)
    at StudentD.enterl(StudentD.java:122)
    at StudentD.main(StudentD.java:50)
    But I can't find a problem with the method fillspace, it's just copy/pasted from a working program.
    PROGRAM 1: (StudentD.java)
    import java.text.*;
    import java.io.*;
    import java.awt.*;
    import hsa.Console;
    public class StudentD
    static Console c;
    static String firstn, lastn;
    static int x, numofrec;
    static double marka, markt, markc, markk, marke;
    static String control[] = new String [165];
    static Arecord student;
    static DecimalFormat y = new DecimalFormat ("##.##");
    public static void main (String[] args) throws IOException
    c = new Console ();
    String line;
    int choice = 0;
    BufferedReader fileinput = new BufferedReader (new FileReader ("studentmirror.txt"));
    line = fileinput.readLine ();
    numofrec = Integer.valueOf (line).intValue ();
    for (x = 1 ; x <= numofrec ; x++)
    control [x] = fileinput.readLine ();
    fileinput.close ();
    do
    c.println ("\nMain Menu");
    c.println ("2. Enter Initial List of Students"); // This is where the problem starts
    c.println ("7. Exit Program");
    c.println ("\nWhat would you like to do?");
    choice = c.readInt ();
    if (choice == 2)
    enterl ();
    if (choice == 7)
    c.clear ();
    while (choice != 7);
    PrintWriter fileoutput = new PrintWriter (new FileWriter ("studentmirror.txt"));
    fileoutput.println (numofrec);
    for (x = 1 ; x <= numofrec ; x++)
    fileoutput.println (control [x]);
    fileoutput.close ();
    c.println ("Thank you for using this program, I hope you enjoyed it! :)");
    public static void enterl () throws IOException
    c.clear ();
    String cont;
    c.println ("Caution, this will delete the previous list of students and marks... do you wish to continue? (Y/N)");
    cont = c.readLine ();
    if (cont.equals ("N"))
    c.println ("\nNo records will be deleted or changed.");
    if (cont.equals ("Y"))
    RandomAccessFile houseFile = new RandomAccessFile ("house.jsd", "rw");
    int numofst = 0;
    numofrec = 0;
    boolean pass = false;
    c.println ("\nHow many students would you like to start the list with? (1-15)");
    numofst = c.readInt ();
    if (numofst >= 1 && numofst <= 15)
    pass = true;
    if (pass == false)
    c.println ("\nI'm sorry, but the number you entered is not between 1 and 15, please try again.");
    if (pass == true)
    for (x = 1 ; x <= numofst ; x++)
    numofrec++;
    c.println ("\n" + x + ". What is the student's first name?");
    firstn = c.readLine ();
    firstn = control [numofrec];
    c.println ("\nWhat is the student's last name?");
    lastn = c.readLine ();
    student = new Arecord (numofrec, firstn, lastn, 0, 0, 0, 0, 0);
    houseFile.seek ((long) numofrec * Arecord.recordSize ());
    student.write (houseFile); // This is where the program stops.
    pause ();
    public static void pause ()
    char ch;
    // Pauses the program until the user presses enter
    c.println ("\nPress ENTER to continue...");
    ch = c.readChar ();
    c.clear ();
    NOTE: I've taken out most of the program and only included what you need to use :)
    PROGRAM 2: (Arecord.java)
    import java.io.*;
    import java.awt.*;
    import hsa.Console;
    public class Arecord
    protected int numofrec;
    protected String firstn;
    protected String lastn;
    protected double marka;
    protected double markt;
    protected double markc;
    protected double markk;
    protected double marke;
    protected static final int RECORD_SIZE = 57;
    public Arecord (RandomAccessFile input) throws IOException
    numofrec = input.readInt ();
    byte[] firstnBytes = new byte [15];
    input.readFully (firstnBytes);
    firstn = new String (firstnBytes, 0);
    byte[] lastnBytes = new byte [15];
    input.readFully (lastnBytes);
    lastn = new String (lastnBytes, 0);
    marka = input.readDouble ();
    markt = input.readDouble ();
    markc = input.readDouble ();
    markk = input.readDouble ();
    marke = input.readDouble ();
    public Arecord (int numofrec, String firstn, String lastn, double marka, double markt, double markc, double markk, double marke)
    this.numofrec = numofrec;
    this.firstn = firstn;
    this.lastn = lastn;
    this.marka = marka;
    this.markt = markt;
    this.markc = markc;
    this.markk = markk;
    this.marke = marke;
    public int getNumofrec ()
    return numofrec;
    public String getFirstn ()
    return firstn;
    public String getLastn ()
    return lastn;
    public double getMarka ()
    return marka;
    public double getMarkt ()
    return markt;
    public double getMarkc ()
    return markc;
    public double getMarkk ()
    return markk;
    public double getMarke ()
    return marke;
    public static int recordSize ()
    return RECORD_SIZE;
    public void write (RandomAccessFile output) throws IOException
    output.writeInt (numofrec);
    firstn = fillspace (firstn, 15);
    byte[] firstnBytes = new byte [15];
    firstn.getBytes (0, firstn.length (), firstnBytes, 0);
    output.write (firstnBytes);
    lastn = fillspace (lastn, 15);
    byte[] lastnBytes = new byte [15];
    lastn.getBytes (0, lastn.length (), lastnBytes, 0);
    output.write (lastnBytes);
    output.writeDouble (marka);
    output.writeDouble (markt);
    output.writeDouble (markc);
    output.writeDouble (markk);
    output.writeDouble (marke);
    public static String fillspace (String word, int lengthtofill)
    int stringlength, x;
    stringlength = word.length (); // This is where the error is supposedly happening?
    for (x = stringlength ; x <= lengthtofill - 1 ; x++)
    word = word + " ";
    return word;
    Thanks again to anyone who tries to help! It's probably going to be something incredibly stupid... but hey. :D
    Blessings!
    Sarah

    stringlength = word.length (); // This is where the error is supposedly happening?And it's a NullPointerException? Then the variable "word" is null. It's a parameter of the method, so it must be the case that the code that calls the method is passing a null value.
    The stacktrace tells you that the calling method is "write". At line 104, for those of us who have line numbers (that's you). That could be this line of code:firstn = fillspace (firstn, 15);for example; if this were line 104, that would mean that "firstn" is null. There's another call later in the method which uses "lastn" instead of "firstn", which could also be the problem.

  • RandomAccessFile difficulty

    I'm having a bit of trouble with random access files. When I write the long values 9 or 11, everything below works fine. But with the value 10, I get an end of file exception. Anyone know what I might be doing wrong? It's so strange to me I'm wondering if it might not be a bug of the runtime.
    Code to write
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
                raf.seek(0);
                String sInit = "somename.kdb!%!";
                raf.write(sInit.getBytes());
                raf.writeLong(10);
                raf.close();Code to read
    File f = new File("somename");
                RandomAccessFile raf = new RandomAccessFile(f, "rw");
                raf.seek(0);
                while(!bFound && (sTemp = raf.readLine()) != null){
                    iStringIndex = -1;
                    iStringIndex = sTemp.indexOf("!%!");
                    sData = sTemp.substring(0, iStringIndex);
                    if(sData.equals("somename.kdb")){
                        long lPosition = raf.getFilePointer()-(sTemp.length()-sData.length())+3;
                        raf.seek(lPosition);
                        long lTemp = raf.readLong();
                        System.out.println("lTemp:  "+lTemp);
                }As a note, when I write 10 (with or without an l at the end), the value of lPosition is 16 instead of 15, as is the case with the other values (9 and 11), which is also strange.
    Actually, writing this, I dug a lil deeper. Seems sTemp.length is one size smaller with a value of 10 then with a value of 11 or 9, which makes the readLong start at the wrong index later.
    I'd love to know why it does that though. What's so special about 10? Any insight appreciated.

    Ahh, thank you.
    Well, actually, you're kind of right. I guess it was kind of wring of me to do that. I was trying to set up a key-value pair. I know the value will always be a long, but I can't insure the length of the key (although maybe I should do just that), which is a string. So my reasoning was to read the whole line, knowing reading the long as a string that way would return to me some gibberish, then parse the string using some special character (!%!) to know what my key was. Then, once I'd find my key, I would simply recalculate the position of the pointer and read the long as a long this time around.
    Now, I'm thinking since strings might interpret long values, as you said, I should instead just write a string long enough as bytes of some predefined length, then read that instead of the whole string.

  • RandomAccessFile on Server..Where is File Created?

    Hello Professionals:
    I have created an oracle trigger on a table during insert that passes the column contents to a java procedure that is intended to write this data to a RandomAccessFile. I am not sure where the file will be created on the Server. I created my java classes on an Oracle 8.1.6 database. My java class (and procedure) that writes the data to the file is indicated below. Your guidance is needed. Thanks.
    Chris
    package mypackage1;
    import java.io.*;
    public class AddData
    public static void TriggerData(int v_id, String v_name)
    Record blank;
    String fileName = "TriggerData20.dat";
    blank = new Record(v_id,v_name);
    try {
    RandomAccessFile file = new RandomAccessFile(fileName, "rw");
    file.seek(file.length());
    System.out.println("Just getting ready to write to file");
    blank.write(file);
    System.out.println("Just written data to file");
    System.exit(0);
    catch (IOException e){
    System.out.println("This is not a valid file");
    System.exit(1);
    public static void main(String[] args)
    AddRecord addRecord = new AddRecord();
    // A class that represents one record of information.
    package mypackage1;
    import java.io.Serializable;
    public class AccountRecord implements Serializable
    private int account;
    private String firstName;
    public AccountRecord()
    this(0,"");
    public AccountRecord(int acct, String first)
    setAccount(acct);
    setFirstName(first);
    public void setAccount(int acct)
    account = acct;
    public int getAccount(){return account;}
    public void setFirstName(String first)
    firstName = first;
    public String getFirstName(){return firstName;}
    //Record class for RandomAccessFile programs;
    //This class will be wrapped as a procedure to call in the Oracle Trigger;
    //Two or more values will be passed into the method call Record(xx,xx,etc) from the Oracle table;
    package mypackage1;
    import java.io.*;
    //import AccountRecord class from package!!!!!!!!!!!!!!!!!
    public class Record extends AccountRecord
    //String file = "TriggerData5.dat";
    public Record()
    this(25,"farting");
    public Record(int acct, String first)
    super(acct,first);
    //Read a record from the specified RandomAccessFile
    setAccount(file.readInt() );
    setFirstName(padName(file) );
    private String padName(RandomAccessFile f) throws IOExeption
    char name[] = new char [15], temp;
    for (int i = 0; i < name.length; i++) {
    temp = f.readChar();
    name[i] = temp;
    return new String(name).replace('\0',' ' );
    //Write a record to the specified RandomAccessFile
    public void write(RandomAccessFile file) throws IOException
    //file.seek(size());
    file.writeInt(getAccount() );
    writeName(file, getFirstName() );
    private void writeName(RandomAccessFile f, String name) throws IOException
    StringBuffer buf = null;
    if (name != null )
    buf = new StringBuffer(name);
    else
    buf = new StringBuffer(15);
    buf.setLength(15);
    f.writeChars(buf.toString() );
    /*//Not too sure if I need to have the main method here!!!!!!!!!!!!!!
    public static void main(String[] args)
    Record record = new Record();
    }

    per OracleJVM development: the file will be created with a root of $ORACLE_HOME if the filename is not an absolute
    path. The writer must have the proper permissions to write the file. All subdirectories, if any in the path name, must exist or an
    exception will be thrown.
    My guess is that they would get written into the user_dump_dest directory.
    Probably a question that will be answered most quickly by the RDBMS forum,
    or by a quick test on your database with a file with a well-known name.

  • How to get name of RandomAccessFile?

    Hello. java.io.File has a method: getName() which returns a string assigned to the name of the File. Is there an equivalent for instances of RandomAccessFile? If not, is there some way to get the name of a RandomAccessFile?
    Thanks in advance for your help.
    c00p

    there is no way to get the name of the File associated w/ the RandomAccessFile directly although you could keep track of the File object used to create the RandomAccessFile object in the first place...for example...
    File file = new File("something.txt");
    RandomAccessFile raf = new RandomAccessFile(file, "rw");the variable file refers to the File associated w/ the RandomAccessFile...if you want the File name you could just use file.getName() knowing this is the file the RandomAccessFile is connected to...

  • Update XML using DOM or RandomAccessFile

    Morning,
    One of my server apps stores client resource data in an XML file. Quite often, a process will want to update, add, or remove nodes based upon requirement. Is it less efficient to load the entire XML document into the DOM and modify it or just use RandomAccessFile to search for specific byte patterns and perform my modifications?
    Or, does it really matter? Using the DOM would be more in keeping with its intended purpose vs the more direct byte by byte approach.
    Thank you,
    Stig.

    Well, if all of your modifications are guaranteed to preserve the length of every node in the document, then I suppose you could use a RandomAccessFile. But if somebody someday is going to ask for a text node to be changed from "Mary" to "Maria" then a RandomAccessFile would be just a huge pain. You would have to move everything after that node one char to the right.
    I'm betting your requirements fail that length-preservation test. Especially since you mentioned adding and removing nodes. Just use the DOM already.

Maybe you are looking for

  • Help with 10.4.8

    i'm a design student so i have to use Adobe CS2 A LOT...and before my macbook pro updated to 10.4.8, Adobe Illustrator CS2 was running perfectly fine. but now that it's updated, i can't create pathfinders and i cannot run illustrator and photoshop at

  • JavaScript: Is there a way to move text from de clipboard to a js variable ?

    Now I use an alternative that is (roughly): 1. Save the actual insertionPoint (where I want to put the final result) 2. Create (or use a predefined) textframe off of the page. 3. Select that textFrame and paste the clipboard contents 4. Reselect the

  • ITunes can't restore iPod mini

    I had to restart the player in disk mode to be able to connect it/see it in iTunes. When attempting to restore my iPod mini 4GB, iTunes 9.1 (79) lies saying that the player 'cannot be restored because it contains files that are in use by another appl

  • Sub contracting challen issue excise modvat

    Hi, Please give me solution for below error. Excise modvat accounts not defined for 57FC transaction and D1 excise group Message no. 8I402 SAM

  • Thought on idea exchange "duplicates"

    I'm not really sure where to post this so... I think it would be beneficial if when an idea exchange idea is marked as duplicate, kudos that have been given to the duplicate idea should be transfered to non-duplicate (i.e. original idea). Is this don