Searching in RandomAccessFile

Hi ...... can somebody help me plz about RandomAccessFile ... how can we search a specific record from a randomAccessFile
For example ......I have following code ......
String s1 = JtextField.getText();
File file = new File("file");
RandomAccessFile raf = new RandomAccessFile(file,true);
raf.seek(file);
raf.writeChars(s1);
raf.close();
If I want to search s1 from File ��.what should do I �..????
Thanks in Advance for your kind attention and help ��
ARSHOO

Hi,
Why not write a carriage return between each entry into that file using rafname.writeBytes(System.getProperty("line.separator")); And then search for your entry using the readLine() method.
Eg:
String s;
while(true)
     if((s = raf.readLine()) == null){ break;}
          if (s.equals("whateveryou'relookingfor"))
System.out.println("Found");

Similar Messages

  • Searching binary data file

    Hi I have a data file which acts as a database. I need to search this file for records. I am trying to implement this in the most efficient way I have the following extremes
    1)To search using RandomAccessFile each record directly from the file
    2)Load the entire file into memory. By encapsulating each record in a lava object.
    1st option would save me a lot of memory but time consuming . The second option would consume a lot of memory and might be unsuitable for a large amount of records.
    I have chosen a middle path but I am not sure if it will work properly.
    My current proposal is to use a scaled down Object to represent a record
    Integer values which are mostly 8 bit and 16 bit value will be stored an a array of integers where the necessary values are stored and extracted using bitwise operations.
    My problem is characters I was thinking of storing the hash code of the Strings but the search protocol requires that you should be able to search even if a part of the String is given.
    Regarding this problem I looked up the java 1.5 API doc for String.hashCode. Where I determined the hash code of a substring is smaller than of the main String. My question is? Is it possible to use this as a search condition to initially eliminate certain records and then read the character sequence from the file to confirm my match.
    I hope you can understand what I have typed above and any help would be appreciated.

    Why not turn this thing into a database and actually use database drivers to query it, and let the database worry about those kinds of things rather than basically reinvent them yourself?

  • Better approach for storing Messages ?

    Hello all,
    I am developing a Email module which does resembles yahoo or hotmail.
    To my understanding POP3 dosn't support Folder creation and IMAP does. But, i have to go for POP3 only.
    SO, i thought that i have to go for storing it in database(Message Object) as Byte array.
    so, i have created sent fodler, save folder, draft and custom folders all in database for storing all this message as javax.mail.Message object.
    Since i can't store Message object i have created a wraper class which implemets serialization.
    Now my questions is
    1. is my approach for folder with database is correct ?
    2. if yes, then is it good to store Wraper class as a hole in database. or can i go for divinding the message into parts and store invidualy in database.
    3. if my approach is wrong then how can i go about ?
    awaiting for everybody's reply
    dina

    When through your thinking before :)
    The correct way is to save Message object to disk, i.e cache so we
    don't read from server. To save to database is your choice but it's
    extra overhead. And if you intend client is going to install the
    program on their desktop, database is out of the question.
    The secret is making a simple database design as explain below, like
    Microsoft outlook.pst or look at Netscape cache folders to see their
    design too. Similar...
    Message object is not savable, i.e not implemting serialization but
    their is a way to save the mail messages to disk.
    We use the writeTo method of MimeMessage class to save the whole
    email, including attachments as one whole object stream.
    I use one file for each mail folder, like Microsoft and Netscape does..
    The reason is we might want to copy the whole inbox, which in effect
    is copying the one file to another folder for backup etc...
    Same reason for compressions
    So you might ask, one file, that inefficient isn't it?
    Not really it's how you design it.
    Your mail file should have lookup keys of message id's of your message
    objects. Hence, with message id in a file one can get the ObjectOutputStream in a file with a simple lookup. We use object output
    stream as message class writeTo, writes to output stream, and using
    ObjectOutputStream to store and retrieve makes a whole lot of sense.
    The cahce mail storage should be using a RandomAccessFile and their
    are package classes you can download from JavaWorld to have access
    to writing and reading object streams from a file using the random
    access file. So no need to worry about database as it does the
    hard work for you. Search for RandomAccessFile in JavaWorld and
    dowload that package.
    RandomeAccessFile class is quite differently to other IO classes as
    it does fast seeking, i.e the file points to different positions of
    the file very quickly. Even if you inbox file is 70 megs big, it can
    still handle it very quickly.
    This should help you clear most of the design problems that I also
    ponder for quite some time

  • Search,edit,delete in randomaccessfile

    This might be too simple to anyone out there but im new in Java.
    I have a text file like below (20041110.txt).
    BSD1,123456789,A1,,0,
    galt,%123456789,A1,,0,
    gal,A,A1,,0,
    gal,B,B1,,0,
    gal,A,A1,,0,
    galt,040,A1,,0,
    I have 3 different things i might want to do in this file. I want
    to save on the same file also.
    1. I need to find and replace a string "%" to "0" (line 2)
    2. I need to delete a duplicate record (line 3 and line 5)
    3. I might encounter a 3 digit number like (040) and changed it
    to a 10 digit number. (line 6)
    I am looking on some example of RandomAccessFile that can do this thing.
    Any useful website links also is appreciated. Something meaningful than
    Java.world.
    Thanks. Any help is appreciated.
    emaj

    Read the existing file and modify a line at at time, writing each line to a new file. When complete, delete the old (existing) file and rename the new file.
    As an alternative, if the file isn't great big, you could write the changes to, say, a String array in memory, then when finished write the array to the old (existing) file, overwriting the contents.
    Or - there are variations on these approaches...

  • 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

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

  • How to search every file on a computer in java

    Hey guys, right now im writing a mac antivirus (i mostly use windows)
    i have the test code to search for hex code clips i have another file to use so i can replace it using a updater to make getting new virus terms more easy. but what it the way to go through and read every file? i can set a file, but i need a way for it to run though the computer like a read antivirus
    plz help guys, you guys are the best

    ohh so u know im not lying, his was a first draught from a while ago
    import java.io.*;
    class AntiVirus
        public static void main (String args[])
              //bin = new Signature(file);
              File f = new File("junk.dll");
              //File f = new File("Test20041025.java");
              if ((int)f.length() > Integer.MAX_VALUE) {
                   System.out.println("Not enough memory to read file.");
                   System.exit(-1);
              byte[] bytes = new byte[(int)f.length()]; // assume < 2gb
              RandomAccessFile raf = null;
              try
                    raf = new RandomAccessFile(f,"r");
                    raf.readFully(bytes);
                    raf.close();
              catch (Exception e)
                   System.out.println(e.toString());
                   System.exit(-1);
              //String result = new String(bytes /*, encoding*/ );
              //byte[] testPatternB = new byte[testPatternS.length];
              int[] testPatternS = { 0x07, 0x08, 0x09, 0xAB, 0xBF, 0x62, 0x04 };          
              byte[] testPatternB = new byte[testPatternS.length];
              int[] testPatternS2 = { 0x07, 0x08, 0x09, 0xAB, 0xBF, 0x62, 0x04 };          
              byte[] testPatternB2 = new byte[testPatternS.length];
              for (int i = 0; i < testPatternS.length; i++)
                   testPatternB[i] = (byte)testPatternS;
              for (int i = 0; i < testPatternS2.length; i++)
                   testPatternB2[i] = (byte)testPatternS2[i];
              String pattern = new String(testPatternB);
              String fileBytes = new String(bytes);
              String pattern2 = new String(testPatternB2);
              //System.out.println(fileBytes.indexOf(pattern));
              if(fileBytes.indexOf(pattern) > 0 && fileBytes.indexOf(pattern2) > 0 ) // if a file is found it its a random number 1-??? so i do a check to tell
              System.out.println("You Have a Serios Virus");

  • Search for a String in a File?

    hi all
    is there a methid in java with which i can open a file and
    search for a specified string in the file? i also have to
    replace the String then.
    Thanks angela

    There is no magic method that can do all this for you. First you need to create an inputstream from the file you want to read. Then you can read it (without necessarily store the whole file in memory), until you find a match. If you want to replace the string with another string of the same length, you can use RandomAccessFile. If not, then you will have to move all the rest of the file forward or backwards when you replace the string, or write the whole file modified to a new file and then delete the old file before you rename the new updated file.
    Or you can depending on what you do, append changes to the end of the file, more or less like what is done with Word documents. And then only once in a while update the file with all the appended changes.

  • Binary search in text files

    Hi all,
    I'm thinking about how to implement a binary sort to get,given a key, a value from a text file with a list of words in order. I saw randomaccessfile for j2se and I know that this work it's usually done by seek functions but how to do the seek work without the File class , with only the InputStream and Reader? I'm talking about the j2me midp 2 cldc 1.1 api, is there some methods or class to use for this thing? How could be implemented a binary search in a text file resident in the /res dir or the JAR or which could be the problems that cannot make possible this staff? If there was something like seek one way could be that one of decide a common length of words to read so going to the half of the text file it's possible with simply multiplication, and the do the binary search things.But for now I haven't found any resources or help.
    I hope you can help me to understand, thank you

    Hallo all,
    it is NOT the problem to locate the text I need to find in the fmb, or fmx.
    The problem is that since I want to change not only the text but also some more code around I want to do this in Form Builder - Object Navigator. And I'm not able to discover in which trigger or procedure the text appears.
    I do not want to edit fmx, or fmb in a text editor because I suupose theer are some checksums hidden for the format.
    -duro
    BTW in FMT there is no code seen (only some binary) for v6i as it was in v4.5.

  • Binary search in files

    Is there a way of executa a binary search directlly over a file ? a java native way ?

    That would work best with a RandomAccessFile, since a binary search jumps back and forth looking at different places in the search space. And it would have to be a RandomAccessFile with fixed record lengths, sorted in the correct sequence. There is no method in the standard API to do that, but you could write the binary search code without much difficulty.

  • Binary search in a text file.

    Is it possible to carry out binary search directly in the text file without passing the file data into a List data, in order to save RAM?

    If the file is sorted, and if you know what byte position each record begins at, then, yes, using RandomAccessFile you can do this.
    I don't know if it's really the best approach though. If the file's not all that big, or if the relevant parts of its content can be represented in more compact form, then sorting in memory will be simpler and quicker.

  • 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.

  • RandomAccessFile writes only around 2024  lines!

    Hi all,
    I have a slight problem.
    I have created a little program that helps me with some processing. I had a file with a list of 8000 products (some occuer more than once), and a seperate file with a list of prices for each of the products (in mixed up order). So wot I did was read the first product from the product file and then search for the price in the second file, get the value and write to a third file the product and the price with a tab in between (to create a tab delimited file).
    I am using 3 RandomAccessFiles, 2 i read from using raf.readLine() method and 1 write to using raf.writeChars(string)
    Everytime after writing line 2024 (or 2025) i get an IOException...
    (this happens after about a couple of mins as the alogirthm is quite slow but that doesnt concern me, better than sitting a whole month editing in Excel)
    Can anyone help??

    Thankyou for your help, i've worked out the problem.
    i was opening a randomaccessfile in a while loop without closing it!
    So was ending up with too many open files after 2025 or files open it gives up. n e way i fixed the problem.
    much appreciated.

Maybe you are looking for

  • How do I create a package that will install a shell script?

    From various sources I have made this shell script which creates a hidden admin user, starts ard and sshd. I would like to make this a package which will run on a machine on first boot. (I'm using deploystudio to deploy ML) It creates a hidden user c

  • HT201272 Only part of a song downloaded from itunes store

    Only part of a song (the first 12 seconds) downloaded and I nothing in my download list.  How can i download the entire song?

  • Basic on interactive reporting

    hi i am new to IR.........can any one guide me abt IR.....whts abt feature....pls guide me..iam new for IR...

  • Define Fixed Values for Texts

    Hello, Using customizing for text schema, it is possible to define fixed values for texts from SRM document. Nevertheless, when you define fixed values for a transaction type, field "Fixed Value for a Text" is a CHAR30 data type. Is there a way to ad

  • Recipe app on the TX2Z notebook

    We were looking tthe TX2Z as a kitchen recipe book, but I noticed that the recipe software does not come bundled with it. Is it available for download?