Writing data in Random Access File

I was reading something about Random Access File coz I wanted to practice file handling in java. like, writing a data in a random access file, deleting the stored data, updating the stored data and search for a specific data.. I wasn't able to understand the example because the book gave a large program and it's not explained in detail. Is there any good tutorials that you could recommend for me?

http://www.google.com/search?q=java+RandomAccessFile+example&hl=en&sourceid=gd&rls=GGLD,GGLD:2008-06,GGLD:en
How did we get anything done before google?

Similar Messages

  • Moving data in random access file

    Hi All
    I am back again with the same query of RandomAccessFile.
    I want to move data in the by n bytes. How do I do this. Like I want to add data somewhere in middle of file. I am reaching at the point using seek() method and writing the data also. But the next line is getting overwritten. So I want to moves the data in file first and write my data.
    Please help me with logic or Code sniippet. I am struggling with this for past 2 weeks.
    Thanks in Advance
    With regards
    Shashi

    RandomAccessFile doesn't offer an insert facility, so
    you'll need to work around, such as create a
    temporary copy of the file by writing the file's
    head, your data to be inserted, and the file's tail,
    then delete the old file and rename the copy.When you stare at this a bit, you'll see this post is actually saying
    the same as mine :-)

  • Random access files

    This program is supposed to retrieve data from TelephoneUI's JTextFields, store the data in a RandomAccessRecord class object record and call the write method of class RandomAccessRecord to output the data.
    Two questions
    Is there any way to check if the data was actually written to the file without writing a new class to read the file?
    How can I make it so that the file-position pointer for object output start from byte 0 for the first record and move 94 bytes after each read? Right now the file-position pointer moves 94 bytes after each read but starts from 94.
    public class WriteRandomFile extends JFrame {  
       private RandomAccessFile output;
       private TelephoneUI userInterface;
       private JButton enterButton, openButton;
       // set up GUI
       public WriteRandomFile()
          super( "Write to random access file" );
          // create instance of reusable user interface TelephoneUI
          userInterface = new TelephoneUI(4);  // four textfields
          getContentPane().add( userInterface,
             BorderLayout.CENTER );
          // get reference to generic task button doTask1 in TelephoneUI
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Open..." );
          // register listener to call openFile when button pressed
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // allow user to select file to open
                public void actionPerformed( ActionEvent event )
                   openFile();
             }  // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add record in TelephoneUI, then close file
                public void windowClosing( WindowEvent event )
                   if ( output != null )
                      addRecord();
                   closeFile();
             }  // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 in TelephoneUI
          enterButton = userInterface.getDoTask2Button();
          enterButton.setText( "Enter" );
          enterButton.setEnabled( false );
          // register listener to call addRecord when button pressed
          enterButton.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // add record to file
                public void actionPerformed( ActionEvent event )
                   addRecord();
             }  // end anonymous inner class
          ); // end call to addActionListener
          setSize( 300, 150 );
          show(); 
       // enable user to choose file to open
       private void openFile()
          // display file dialog so user can select file
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode(
             JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null ||
               fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this,
                "Invalid File Name", "Invalid File Name",
                JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new RandomAccessFile( fileName, "rw" );
                enterButton.setEnabled( true );
                openButton.setEnabled( false );
             // process exception while opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this,
                   "File does not exist",
                   "Invalid File Name",
                   JOptionPane.ERROR_MESSAGE );
       }  // end method openFile
       // close file and terminate application
       private void closeFile()
          // close file and exit
          try {
             if ( output != null )
                output.close();
               System.exit( 0 );
          // process exception while closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       // add one record to file
       public void addRecord()
          String fields[] = userInterface.getFieldValues();
          RandomAccessRecord record =
             new RandomAccessRecord();
          int count = 1;
          // ensure field has a value
          if ( ! fields[ TelephoneUI.LASTNAME ].equals( "" ) ) {
             // output values to file
             try {
                   record.setFirstName( fields[ TelephoneUI.FIRSTNAME ] );
                   record.setLastName( fields[ TelephoneUI.LASTNAME ] );
                   record.setAddress( fields[ TelephoneUI.ADDRESS ] );
                   record.setPhone( Integer.parseInt( fields[ TelephoneUI.PHONENUMBER ] ) );
                             count = count * 94;
                             output.seek( count );
                   record.write( output );
                userInterface.clearFields();  // clear TextFields
             // process improper account number or balance format
             catch ( NumberFormatException formatException ) {
                    JOptionPane.showMessageDialog( this,
                       "Bad account number or balance",
                       "Invalid Number Format",
                       JOptionPane.ERROR_MESSAGE );
             // process exceptions while writing to file
             catch ( IOException ioException ) {
                closeFile();
       }  // end method addRecord
       // execute application
       public static void main( String args[] )
          new WriteRandomFile();
    }  // end class WriteRandomFile

    This program is supposed to retrieve data from
    TelephoneUI's JTextFields, store the data in a
    RandomAccessRecord class object record and call the
    write method of class RandomAccessRecord to output
    the data.
    Two questions
    Is there any way to check if the data was actually
    written to the file without writing a new class to
    read the file? Why? If the io operations are not working (and not throwing exceptions) then you might as well give up.
    >
    How can I make it so that the file-position pointer
    for object output start from byte 0 for the first
    record and move 94 bytes after each read? Right now
    the file-position pointer moves 94 bytes after each
    read but starts from 94.Huh? It moves 94 and you want it to move 94?
    Perhaps you are just looking for the getFilePointer() and seek() methods?
    >
    public class WriteRandomFile extends JFrame {
    private RandomAccessFile output;
    private TelephoneUI userInterface;
    private JButton enterButton, openButton;
    // set up GUI
    public WriteRandomFile()
    super( "Write to random access file" );
    // create instance of reusable user interface
    erface TelephoneUI
    userInterface = new TelephoneUI(4);  // four
    / four textfields
    getContentPane().add( userInterface,
    BorderLayout.CENTER );
    // get reference to generic task button doTask1
    oTask1 in TelephoneUI
    openButton = userInterface.getDoTask1Button();
    openButton.setText( "Open..." );
    // register listener to call openFile when
    e when button pressed
    openButton.addActionListener(
    // anonymous inner class to handle
    to handle openButton event
    new ActionListener() {
    // allow user to select file to open
    public void actionPerformed( ActionEvent
    ActionEvent event )
    openFile();
    }  // end anonymous inner class
    ); // end call to addActionListener
    // register window listener for window closing
    losing event
    addWindowListener(
    // anonymous inner class to handle
    to handle windowClosing event
    new WindowAdapter() {
    // add record in TelephoneUI, then close
    , then close file
    public void windowClosing( WindowEvent
    WindowEvent event )
    if ( output != null )
    addRecord();
    closeFile();
    }  // end anonymous inner class
    ); // end call to addWindowListener
    // get reference to generic task button doTask2
    oTask2 in TelephoneUI
    enterButton =
    tton = userInterface.getDoTask2Button();
    enterButton.setText( "Enter" );
    enterButton.setEnabled( false );
    // register listener to call addRecord when
    d when button pressed
    enterButton.addActionListener(
    // anonymous inner class to handle
    to handle enterButton event
    new ActionListener() {
    // add record to file
    public void actionPerformed( ActionEvent
    ActionEvent event )
    addRecord();
    }  // end anonymous inner class
    ); // end call to addActionListener
    setSize( 300, 150 );
    show(); 
    // enable user to choose file to open
    private void openFile()
    // display file dialog so user can select file
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(
    JFileChooser.FILES_ONLY );
    int result = fileChooser.showOpenDialog( this
    ( this );
    // if user clicked Cancel button on dialog,
    ialog, return
    if ( result == JFileChooser.CANCEL_OPTION )
    return;
    // obtain selected file
    File fileName = fileChooser.getSelectedFile();
    // display error if file name invalid
    if ( fileName == null ||
    fileName.getName().equals( "" ) )
    JOptionPane.showMessageDialog( this,
    "Invalid File Name", "Invalid File
    Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    else {
    // open file
    try {
    output = new RandomAccessFile( fileName,
    e( fileName, "rw" );
    enterButton.setEnabled( true );
    openButton.setEnabled( false );
    // process exception while opening file
    catch ( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "File does not exist",
    "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    }  // end method openFile
    // close file and terminate application
    private void closeFile()
    // close file and exit
    try {
    if ( output != null )
    output.close();
               System.exit( 0 );
    // process exception while closing file
    catch( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "Error closing file",
    "Error", JOptionPane.ERROR_MESSAGE );
    System.exit( 1 );
    // add one record to file
    public void addRecord()
    String fields[] =
    ds[] = userInterface.getFieldValues();
    RandomAccessRecord record =
    new RandomAccessRecord();
    int count = 1;
    // ensure field has a value
    if ( ! fields[ TelephoneUI.LASTNAME ].equals(
    quals( "" ) ) {
    // output values to file
    try {
    record.setFirstName( fields[
    stName( fields[ TelephoneUI.FIRSTNAME ] );
    record.setLastName( fields[
    stName( fields[ TelephoneUI.LASTNAME ] );
    record.setAddress( fields[
    ddress( fields[ TelephoneUI.ADDRESS ] );
    record.setPhone( Integer.parseInt(
    teger.parseInt( fields[ TelephoneUI.PHONENUMBER ] )
                             count = count * 94;
                             output.seek( count );
    record.write( output );
    userInterface.clearFields();  // clear
    );  // clear TextFields
    // process improper account number or
    number or balance format
    catch ( NumberFormatException
    Exception formatException ) {
    JOptionPane.showMessageDialog( this,
    "Bad account number or balance",
    "Invalid Number Format",
    JOptionPane.ERROR_MESSAGE );
    // process exceptions while writing to file
    catch ( IOException ioException ) {
    closeFile();
    }  // end method addRecord
    // execute application
    public static void main( String args[] )
    new WriteRandomFile();
    }  // end class WriteRandomFile

  • Modify Record Number in a Random Access File

    Hi Does anyone know if I can modify the record number in the random access file hardware.dat for each hardware record each time and update it in hardware.dat to display it? Also why does it say "Record does not exist" if I modify the record number for a hardware and try to update it but could not find that record?
    Here is the code below:
    // Exercise 14.11: HardwareRecord.java
    package org.egan; // packaged for reuse
    public class HardwareRecord
      private int recordNumber;
      private String toolName;
      private int quantity;
      private double cost;
      // no-argument constructor calls other constructor with default values
      public HardwareRecord()
        this(0,"",0,0.0); // call four-argument constructor
      } // end no-argument HardwareRecord constructor
      // initialize a record
      public HardwareRecord(int number, String tool, int amount, double price)
        setRecordNumber(number);
        setToolName(tool);
        setQuantity(amount);
        setCost(price);
      } // end four-argument HardwareRecord constructor
      // set record number
      public void setRecordNumber(int number)
        recordNumber = number;
      } // end method setRecordNumber
      // get record number
      public int getRecordNumber()
        return recordNumber;
      } // end method getRecordNumber
      // set tool name
      public void setToolName(String tool)
        toolName = tool;
      } // end method setToolName
      // get tool name
      public String getToolName()
        return toolName;
      } // end method getToolName
      // set quantity
      public void setQuantity(int amount)
        quantity = amount;
      } // end method setQuantity
      // get quantity
      public int getQuantity()
        return quantity;
      } // end method getQuantity
      // set cost
      public void setCost(double price)
        cost = price;
      } // end method setCost
      // get cost
      public double getCost()
        return cost;
      } // end method getCost
    } // end class HardwareRecord-------------------------------------------------------------------------------------------------
    // Exercise 14.11: RandomAccessHardwareRecord.java
    // Subclass of HardwareRecord for random-access file programs.
    package org.egan; // package for reuse
    import java.io.RandomAccessFile;
    import java.io.IOException;
    public class RandomAccessHardwareRecord extends HardwareRecord
      public static final int SIZE = 46;
      // no-argument constructor calls other constructor with default values
      public RandomAccessHardwareRecord()
        this(0,"",0,0.0);
      } // end no-argument RandomAccessHardwareRecord constructor
      // initialize a RandomAccessHardwareRecord
      public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
        super(number,tool,amount,price);
      } // end four-argument RandomAccessHardwareRecord constructor
      // read a record from a specified RandomAccessFile
      public void read(RandomAccessFile file) throws IOException
        setRecordNumber(file.readInt());
        setToolName(readName(file));
        setQuantity(file.readInt());
        setCost(file.readDouble());
      } // end method read
      // ensure that name is proper length
      private String readName(RandomAccessFile file) throws IOException
        char name[] = new char[15], temp;
        for(int count = 0; count < name.length; count++)
          temp = file.readChar();
          name[count] = temp;
        } // end for
        return new String(name).replace('\0',' ');
      } // end method readName
      // write a record to specified RandomAccessFile
      public void write(RandomAccessFile file) throws IOException
        file.writeInt(getRecordNumber());
        writeName(file, getToolName());
        file.writeInt(getQuantity());
        file.writeDouble(getCost());
      } // end method write
      // write a name to file; maximum of 15 characters
      private void writeName(RandomAccessFile file, String name) throws IOException
        StringBuffer buffer = null;
        if (name != null)
          buffer = new StringBuffer(name);
        else
          buffer = new StringBuffer(15);
        buffer.setLength(15);
        file.writeChars(buffer.toString());
      } // end method writeName
    } // end RandomAccessHardwareRecord-------------------------------------------------------------------------------------------------
    // Exercise 14.11: CreateRandomFile.java
    // creates random-access file by writing 100 empty records to disk.
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import org.egan.RandomAccessHardwareRecord;
    public class CreateRandomFile
      private static final int NUMBER_RECORDS = 100;
      // enable user to select file to open
      public void createFile()
        RandomAccessFile file = null;
        try  // open file for reading and writing
          file = new RandomAccessFile("hardware.dat","rw");
          RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
          // write 100 blank records
          for (int count = 0; count < NUMBER_RECORDS; count++)
            blankRecord.write(file);
          // display message that file was created
          System.out.println("Created file hardware.dat.");
          System.exit(0);  // terminate program
        } // end try
        catch (IOException ioException)
          System.err.println("Error processing file.");
          System.exit(1);
        } // end catch
        finally
          try
            if (file != null)
              file.close();  // close file
          } // end try
          catch (IOException ioException)
            System.err.println("Error closing file.");
            System.exit(1);
          } // end catch
        } // end finally
      } // end method createFile
    } // end class CreateRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: CreateRandomFileTest.java
    // Testing class CreateRandomFile
    public class CreateRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateRandomFile application = new CreateRandomFile();
         application.createFile();
       } // end main
    } // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.11: MenuOption.java
    // Defines an enum type for the hardware credit inquiry program's options.
    public enum MenuOption
      // declare contents of enum type
      PRINT(1),
      UPDATE(2),
      NEW(3),
      DELETE(4),
      END(5);
      private final int value; // current menu option
      MenuOption(int valueOption)
        value = valueOption;
      } // end MenuOptions enum constructor
      public int getValue()
        return value;
      } // end method getValue
    } // end enum MenuOption-------------------------------------------------------------------------------------------------
    // Exercise 14.11: FileEditor.java
    // This class declares methods that manipulate hardware account records
    // in a random access file.
    import java.io.EOFException;
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.Scanner;
    import org.egan.RandomAccessHardwareRecord;
    public class FileEditor
      RandomAccessFile file; // reference to the file
      Scanner input = new Scanner(System.in);
      // open the file
      public FileEditor(String fileName) throws IOException
        file = new RandomAccessFile(fileName, "rw");
      } // end FileEditor constructor
      // close the file
      public void closeFile() throws IOException
        if (file != null)
          file.close();
      } // end method closeFile
      // get a record from the file
      public RandomAccessHardwareRecord getRecord(int recordNumber)
         throws IllegalArgumentException, NumberFormatException, IOException
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        if (recordNumber < 1 || recordNumber > 100)
          throw new IllegalArgumentException("Out of range");
        // seek appropriate record in a file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        record.read(file);
        return record;
      } // end method getRecord
      // update record tool name in file
      public void updateRecordToolName(int recordNumber, String newToolName)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new IllegalArgumentException("Record does not exist");
        // seek appropriate record in file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        record.setToolName(newToolName);
        record = new RandomAccessHardwareRecord(
           record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
        record.write(file); // write updated record to file
      } // end method updateRecordToolName
      // update record in file
      public void updateRecordQuantity(int recordNumber, int newQuantity)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new IllegalArgumentException("Record does not exist");
        // seek appropriate record in file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        record.setQuantity(newQuantity);
        record = new RandomAccessHardwareRecord(
           record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
        record.write(file); // write updated record to file
      } // end method updateRecordQuantity
      // update record in file
      public void updateRecordCost(int recordNumber, double newCost)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new IllegalArgumentException("Record does not exist");
        // seek appropriate record in file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        record.setCost(newCost);
        record = new RandomAccessHardwareRecord(
           record.getRecordNumber(), record.getToolName(), record.getQuantity(), record.getCost());
        record.write(file); // write updated record to file
      } // end method updateRecordCost
      // add record to file
      public void newRecord(int recordNumber, String toolName, int quantity, double cost)
         throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() != 0)
          throw new IllegalArgumentException("Record already exists");
        // seek appropriate record in file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        record = new RandomAccessHardwareRecord(recordNumber, toolName, quantity, cost);
        record.write(file); // write record to file
      } // end method newRecord
      // delete record from file
      public void deleteRecord(int recordNumber) throws IllegalArgumentException, IOException
        RandomAccessHardwareRecord record = getRecord(recordNumber);
        if (record.getRecordNumber() == 0)
          throw new IllegalArgumentException("Account does not exist");
        // seek appropriate record in file
        file.seek((recordNumber - 1) * RandomAccessHardwareRecord.SIZE);
        // create a blank record to write to the file
        record = new RandomAccessHardwareRecord();
        record.write(file);
      } // end method deleteRecord
      // read and display records
      public void readRecords()
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
        try  // read a record and display
          file.seek(0);
          while (true)
            do
              record.read(file);
            while (record.getRecordNumber() == 0);
            // display record contents
            System.out.printf("%-10d%-15s%-15d%10.2f\n",record.getRecordNumber(),
               record.getToolName(), record.getQuantity(), record.getCost());
          } // end while
        } // end try
        catch (EOFException eofException)  // close file
          return;  // end of file was reached
        } // end catch
        catch (IOException ioException)
          System.err.println("Error reading file.");
          System.exit(1);
        } // end catch
      } // end method readRecords
    } // end class FileEditor-------------------------------------------------------------------------------------------------
    // Exercise 14.11: TransactionProcessor.java
    // A transaction processing program using random-access files.
    import java.io.IOException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.RandomAccessHardwareRecord;
    public class TransactionProcessor
      private FileEditor dataFile;
      private RandomAccessHardwareRecord record;
      private MenuOption choices[] = {MenuOption.PRINT, MenuOption.UPDATE, MenuOption.NEW,
              MenuOption.DELETE, MenuOption.END};
      private Scanner input = new Scanner(System.in);
      // get the file name and open the file
      private boolean openFile()
        try // attempt to open file
          // call the helper method to open the file
          dataFile = new FileEditor("hardware.dat");
        } // end try
        catch (IOException ioException)
          System.err.println("Error opening file.");
          return false;
        } // end catch
        return true;
      } // end method openFile
      // close file and terminate application
      private void closeFile()
        try // close file
          dataFile.closeFile();
        } // end try
        catch (IOException ioException)
          System.err.println("Error closing file.");
          System.exit(1);
        } // end catch
      } // end method closeFile
      // create, update or delete the record
      private void performAction(MenuOption action)
        int recordNumber = 0;  // record number of record
        String toolName;       // tool name of the hardware instrument
        int quantity;          // total amount of items
        double cost;           // hareware tool price
        int choice;            // choose an update option   
        int newRecordNumber;   // the updated record number
        String newToolName;    // the updated tool name
        int newQuantity;       // the updated quantity
        double newCost;        // the updated cost
        try // attempt to manipulate files based on option selected
          switch(action) // switch based on option selected
            case PRINT:
              System.out.println();
              dataFile.readRecords();
              break;
            case NEW:
              System.out.printf("\n%s%s\n%s\n%s","Enter record number,",
                "tool name, quantity, and cost.","(Record number must be 1 - 100)","? ");
              recordNumber = input.nextInt();  // read record number       
              toolName = input.next();         // read tool name
              quantity = input.nextInt();      // read quantity
              cost = input.nextDouble();       // read cost
              dataFile.newRecord(recordNumber, toolName, quantity, cost); // create new record
              break;
            case UPDATE:
              System.out.print("\nEnter record number to update (1 - 100): ");
              recordNumber = input.nextInt();
              record = dataFile.getRecord(recordNumber);
              if (record.getRecordNumber() == 0)
                System.out.println("Record does not exist.");
              else
                // display record contents
                System.out.printf("%-10d%-12s%-12d%10.2f\n\n", record.getRecordNumber(),
                   record.getToolName(), record.getQuantity(), record.getCost());
                System.out.printf("%s%s","\nEnter 1 to update tool name, ",
                  "2 to update quantity, or 3 to update cost : ");
                choice = input.nextInt();
                if (choice == 1)
                  System.out.print("Enter new record tool name : ");
                  newToolName = input.next();
                  dataFile.updateRecordToolName(recordNumber,newToolName); // update record
                                                                           // tool name            
                  // retrieve updated record
                  record = dataFile.getRecord(recordNumber);
                  // display updated record
                  System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
                     record.getToolName(), record.getQuantity(), record.getCost());
                else if (choice == 2)
                  System.out.print("Enter new record quantity : ");
                  newQuantity = input.nextInt();
                  dataFile.updateRecordQuantity(recordNumber,newQuantity); // update record
                                                                           // quantity             
                  // retrieve updated record
                  record = dataFile.getRecord(recordNumber);
                  // display updated record
                  System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
                     record.getToolName(), record.getQuantity(), record.getCost());
                else if (choice == 3)
                  System.out.print("Enter new record cost : ");
                  newCost = input.nextDouble();
                  dataFile.updateRecordCost(recordNumber,newCost); // update record cost            
                  // retrieve updated record
                  record = dataFile.getRecord(recordNumber);
                  // display updated record
                  System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
                     record.getToolName(), record.getQuantity(), record.getCost());
              } // end else     
              break;
            case DELETE:
              System.out.print("\nEnter an account to delete ( 1 - 100): ");
              recordNumber = input.nextInt();
              dataFile.deleteRecord(recordNumber);  // delete record
              break;
            default:
              System.out.println("Invalid action.");
              break;
          } // end switch
        } // end try
        catch (NumberFormatException format)
          System.err.println("Bad input.");
        } // end catch
        catch (IllegalArgumentException badRecord)
          System.err.println(badRecord.getMessage());
        } // end catch
        catch (IOException ioException)
          System.err.println("Error writing to the file.");
        } // end catch
        catch (NoSuchElementException elementException)
          System.err.println("Invalid input. Please try again.");
          input.nextLine();
        } // end catch
      } // end method performAction
      // enable user to input menu choice
      private MenuOption enterChoice()
        int menuChoice = 1;
        // display available options
        System.out.printf("\n%s\n%s\n%s\n%s\n%s\n%s","Enter your choice",
         "1 - List hardware records", "2 - Update a hardware record",
         "3 - Add a new hardware record", "4 - Delete a hardware record", "5 - End program\n?");
        try
          menuChoice = input.nextInt();
        catch (NoSuchElementException elementException)
          System.err.println("Invalid input.");
          System.exit(1);
        } // end catch
        return choices[menuChoice - 1];  // return choice from user
      } // end enterChoice
      public void processRequests()
        openFile();
        // get user's request
        MenuOption choice = enterChoice();
        while (choice != MenuOption.END)
          performAction(choice);
          choice = enterChoice();
        } // end while
        closeFile();
      } // end method processRequests
    } // end class TransactionProcessor-------------------------------------------------------------------------------------------------
    // Exercise 14.11: TransactionProcessorTest.java
    // Testing the transaction processor.
    public class TransactionProcessorTest
      public static void main(String args[])
         TransactionProcessor application = new TransactionProcessor();
         application.processRequests();
      } // end main
    } // end class TransactionProcessorTest-------------------------------------------------------------------------------------------------
    Below is the sample data to be entered into the random input file hardware.dat :
    Record                     Tool                        Quantity                Cost
    Number                   Name                
       3                      Sander                    18                         35.99
      19                      Hammer                128                      10.00
      26                      Jigsaw                   16                        14.25
      39                      Mower                    10                        79.50
      56                      Saw                        8                          89.99
      76                      Screwdriver            236                      4.99
      81                      Sledgehammer       32                        19.75
      88                      Wrench                      65                        6.48Message was edited by:
    egan128
    Message was edited by:
    egan128
    Message was edited by:
    egan128

    Hi Does anyone know if I can modify the record number
    in the random access file hardware.dat for each
    hardware record each time and update it in
    hardware.dat to display it?If the "record number" is data that is stored in the file, then you can modify it. More precisely: it is possible to modify it.
    The rest of the question had too many incompatible verbs for me to understand it.
    Also why does it say
    "Record does not exist" if I modify the record number
    for a hardware and try to update it but could not
    find that record?"Record does not exist" is a fairly reasonable error message for the situation where a program looks for a record but cannot find it. Are you asking why that particular lump of code actually does that?
    (One thousand lines of code removed)

  • Random Access File not working, Need Help!!!!

    I am having trouble creating and displaying a Random Access File for hardware tools. I have included the code below in eight files:
    // Exercise 14.11: HardwareRecord.java
    package org.egan; // packaged for reuse
    public class HardwareRecord
      private int recordNumber;
      private String toolName;
      private int quantity;
      private double cost;
      // no-argument constructor calls other constructor with default values
      public HardwareRecord()
        this(0,"",0,0.0); // call four-argument constructor
      } // end no-argument HardwareRecord constructor
      // initialize a record
      public HardwareRecord(int number, String tool, int amount, double price)
        setRecordNumber(number);
        setToolName(tool);
        setQuantity(amount);
        setCost(price);
      } // end four-argument HardwareRecord constructor
      // set record number
      public void setRecordNumber(int number)
        recordNumber = number;
      } // end method setRecordNumber
      // get record number
      public int getRecordNumber()
        return recordNumber;
      } // end method getRecordNumber
      // set tool name
      public void setToolName(String tool)
        toolName = tool;
      } // end method setToolName
      // get tool name
      public String getToolName()
        return toolName;
      } // end method getToolName
      // set quantity
      public void setQuantity(int amount)
        quantity = amount;
      } // end method setQuantity
      // get quantity
      public int getQuantity()
        return quantity;
      } // end method getQuantity
      // set cost
      public void setCost(double price)
        cost = price;
      } // end method setCost
      // get cost
      public double getCost()
        return cost;
      } // end method getCost
    } // end class HardwareRecord------------------------------------------------------------------------------------------------
    // Exercise 14.11: RandomAccessHardwareRecord.java
    // Subclass of HardwareRecord for random-access file programs.
    package org.egan; // package for reuse
    import java.io.RandomAccessFile;
    import java.io.IOException;
    public class RandomAccessHardwareRecord extends HardwareRecord
      public static final int SIZE = 72;
      // no-argument constructor calls other constructor with default values
      public RandomAccessHardwareRecord()
        this(0,"",0,0.0);
      } // end no-argument RandomAccessHardwareRecord constructor
      // initialize a RandomAccessHardwareRecord
      public RandomAccessHardwareRecord(int number, String tool, int amount, double price)
        super(number,tool,amount,price);
      } // end four-argument RandomAccessHardwareRecord constructor
      // read a record from a specified RandomAccessFile
      public void read(RandomAccessFile file) throws IOException
        setRecordNumber(file.readInt());
        setToolName(readName(file));
        setQuantity(file.readInt());
        setCost(file.readDouble());
      } // end method read
      // ensure that name is proper length
      private String readName(RandomAccessFile file) throws IOException
        char name[] = new char[15], temp;
        for(int count = 0; count < name.length; count++)
          temp = file.readChar();
          name[count] = temp;
        } // end for
        return new String(name).replace('\0',' ');
      } // end method readName
      // write a record to specified RandomAccessFile
      public void write(RandomAccessFile file) throws IOException
        file.writeInt(getRecordNumber());
        writeName(file, getToolName());
        file.writeInt(getQuantity());
        file.writeDouble(getCost());
      } // end method write
      // write a name to file; maximum of 15 characters
      private void writeName(RandomAccessFile file, String name) throws IOException
        StringBuffer buffer = null;
        if (name != null)
          buffer = new StringBuffer(name);
        else
          buffer = new StringBuffer(15);
        buffer.setLength(15);
        file.writeChars(buffer.toString());
      } // end method writeName
    } // end RandomAccessHardwareRecord------------------------------------------------------------------------------------------------
    // Exercise 14.11: CreateRandomFile.java
    // creates random-access file by writing 100 empty records to disk.
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import org.egan.RandomAccessHardwareRecord;
    public class CreateRandomFile
      private static final int NUMBER_RECORDS = 100;
      // enable user to select file to open
      public void createFile()
        RandomAccessFile file = null;
        try  // open file for reading and writing
          file = new RandomAccessFile("hardware.dat","rw");
          RandomAccessHardwareRecord blankRecord = new RandomAccessHardwareRecord();
          // write 100 blank records
          for (int count = 0; count < NUMBER_RECORDS; count++)
            blankRecord.write(file);
          // display message that file was created
          System.out.println("Created file hardware.dat.");
          System.exit(0);  // terminate program
        } // end try
        catch (IOException ioException)
          System.err.println("Error processing file.");
          System.exit(1);
        } // end catch
        finally
          try
            if (file != null)
              file.close();  // close file
          } // end try
          catch (IOException ioException)
            System.err.println("Error closing file.");
            System.exit(1);
          } // end catch
        } // end finally
      } // end method createFile
    } // end class CreateRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: CreateRandomFileTest.java
    // Testing class CreateRandomFile
    public class CreateRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         CreateRandomFile application = new CreateRandomFile();
         application.createFile();
       } // end main
    } // end class CreateRandomFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.11: WriteRandomFile.java
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.NoSuchElementException;
    import java.util.Scanner;
    import org.egan.RandomAccessHardwareRecord;
    public class WriteRandomFile
      private RandomAccessFile output;
      private static final int NUMBER_RECORDS = 100;
      // enable user to choose file to open
      public void openFile()
        try // open file
          output = new RandomAccessFile("hardware.dat","rw");
        } // end try
        catch (IOException ioException)
          System.err.println("File does not exist.");
        } // end catch
      } // end method openFile
      // close file and terminate application
      public void closeFile()
        try // close file and exit
          if (output != null)
            output.close();
        } // end try
        catch (IOException ioException)
          System.err.println("Error closing file.");
          System.exit(1);
        } // end catch
      } // end method closeFile
      // add records to file
      public void addRecords()
        // object to be written to file
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        int recordNumber = 0;
        String toolName;
        int quantity;
        double cost;
        Scanner input = new Scanner(System.in);
        System.out.printf("%s\n%s\n%s\n%s\n\n",
         "To terminate input, type the end-of-file indicator ",
         "when you are prompted to enter input.",
         "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
         "On Windows type <ctrl> z then press Enter");
        System.out.printf("%s %s\n%s", "Enter record number (1-100),",
          "tool name, quantity and cost.","? ");
        while (input.hasNext())
          try  // output values to file
            recordNumber = input.nextInt();  // read record number
            toolName = input.next();         // read tool name
            quantity = input.nextInt();      // read quantity
            cost = input.nextDouble();       // read cost
            if (recordNumber > 0 && recordNumber <= NUMBER_RECORDS)
              record.setRecordNumber(recordNumber);
              record.setToolName(toolName);
              record.setQuantity(quantity);
              record.setCost(cost);         
              output.seek((recordNumber - 1) *   // position to proper
               RandomAccessHardwareRecord.SIZE); // location for file
              record.write(output);
            } // end if
            else
              System.out.println("Account must be between 0 and 100.");
          } // end try   
          catch (IOException ioException)
            System.err.println("Error writing to file.");
            return;
          } // end catch
          catch (NoSuchElementException elementException)
            System.err.println("Invalid input. Please try again.");
            input.nextLine();  // discard input so enter can try again
          } // end catch
          System.out.printf("%s %s\n%s","Enter record number (1-100),",
            "tool name, quantity and cost.", "? ");
        } // end while
      } // end method addRecords
    } // end class WriteRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: WriteRandomFileTest.java
    // Testing class WriteRandomFile
    public class WriteRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         WriteRandomFile application = new WriteRandomFile();
         application.openFile();
         application.addRecords();
         application.closeFile();
       } // end main
    } // end class WriteRandomFileTest-------------------------------------------------------------------------------------------------
    // Exercise 14.11: ReadRandomFile.java
    import java.io.EOFException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import org.egan.RandomAccessHardwareRecord;
    public class ReadRandomFile
      private RandomAccessFile input;
      // enable user to select file to open
      public void openFile()
        try // open file
          input = new RandomAccessFile("hardware.dat","r");
        } // end try
        catch (IOException ioException)
          System.err.println("File does not exist.");
        } // end catch
      } // end method openFile
      // read and display records
      public void readRecords()
        RandomAccessHardwareRecord record = new RandomAccessHardwareRecord();
        System.out.printf("%-10s%-15s%-15s%10s\n","Record","Tool Name","Quantity","Cost");
        try // read a record and display
          while(true)
            do
              record.read(input);
            }while (record.getRecordNumber() == 0);
            // display record contents
            System.out.printf("%-10d%-12s%-12d%10.2f\n", record.getRecordNumber(),
             record.getToolName(), record.getQuantity(), record.getCost());
          } // end while
        } // end try
        catch (EOFException eofException)
          return; // end of file was reached
        } // end catch
        catch (IOException ioException)
          System.err.println("Error reading file.");
          System.exit(1);
        } // end catch
      }  // end method readRecords
      // close file and terminate application
      public void closeFile()
        try // close file and exit
          if (input != null)
            input.close();
        } // end try
        catch (IOException ioException)
          System.err.println("Error closing file.");
          System.exit(1);
        } // end catch
      } // end methode closeFile
    } // end class ReadRandomFile-------------------------------------------------------------------------------------------------
    // Exercise 14.11: ReadRandomFileTest.java
    // Testing class ReadRandomFile
    public class ReadRandomFileTest
       // main method begins program execution
       public static void main( String args[] )
         ReadRandomFile application = new ReadRandomFile();
         application.openFile();
         application.readRecords();
         application.closeFile();
       } // end main
    } // end class ReadRandomFileTest-------------------------------------------------------------------------------------------------
    Below is the sample data to be inputted in the random file:
    Record Tool Name Quantity Cost
    Number
    3 Sander 18 35.99
    19 Hammer 128 10.00
    26 Jigsaw 16 14.25
    39 Mower 10 79.50
    56 Saw 8 89.99
    76 Screwdriver 236 4.99
    81 Sledgehammer 32 19.75
    88 Wrench 65 6.48

    I have managed to fix your program.
    The solution
    The records are sized by the various Writes that occur.
    A record is an int + 15 chars + int + double.
    WriteInt writes 4 bytes
    WriteChar (Called by WriteChars) write 2 bytes
    WriteDouble writes 8 bytes.
    (In Java 1.5 )
    4 bytes + 30 Bytes + 4Bytes + 8 Bytes. = 46 Bytes.
    The details are in the API for Random Acces Files at
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/RandomAccessFile.html
    The code for RandomAccessHardwareRecord line
    public statis final int SIZE = 72needs to have the 72 changed to 46
    This should make your code work.
    I have hacked around with some other bits and will send you my code if you want but that is the key. The asnwers you were getting illustrated a bunch of bytes being read as (say) an int and beacuse of the wrong record length, they were just a bunch of 4 bytes that evaluated to whetever was at that point in the file.
    When the record was written the line
    output.seek((recordNumber -1 ) * RandomAccessHardwareRecord.SIZE);had SIZE as 72 and so the seek operation stuck the file pointer in the wrong place.
    This kind of stuff is good fun and good learning for mentally getting a feel for record filing but in real problems you either serialize your objects or use XML (better) or use jdbc (possibley even better depending on what you are doing).
    I would echo sabre comment about the program being poor though because
    If the program is meant to teach, it is littered with overly complex statements and if it is meant to be a meaningful program, the objects are too tied to hardware and DAO is the way to go. The problem that the program has indicates that maybe it is maybe fairly old and not written with java 2 in mind.
    As for toString() and "Yuk"
    Every class inherits toString() from Object. so if you System.out.println(Any object) then you will get something printed. What gets printed is determined by a complex hieracrchy of classes unless you overRide it with your own method.
    If you use UnitTesting (which would prevent incorrect code getting as far as this code did in having an error), then toString() methods are really very useful.
    Furthermore, IMO Since RandomAccessHardwareRecord knows how to file itself then I hardly think that knowing how to print itself to the console is a capital offence.
    In order to expand on the 72 / 46 byte problem.
    Message was edited by:
    nerak99

  • How to read a mixed text and binary random-access file?

    I have a PDF file which I want to decode. The format is a mixture of binary data and text. What I need is to position the file to a particular position, and then to read from that point as a stream either a set of binary bytes or straight ASCII text. I can't see how to do this (if in fact it's possible).
    I can open the file as a SeekableByteChannel and position it, but opening a stream repositions the file to the beginning - just what I don't want.
    Is there any way of opening a stream from part-way through a file?

    I think that I gave this topic a rather misleading title. What it really should be is "How to turn a random access file into a stream"?
    I realise that I can open an InputStream and skip the relevant number of characters - but this is highly inefficient on a large file where I will skipping about within the file. I need a stream so that I can apply other stream functions to it - buffering in memory will I suspect be too big.

  • How to use random access file to access file in disk?

    I have tried to use random access file stream to access the some files saved in disk, but not very successful. I want to know how I can find a particular file in the disk with file locator or sth else.
    Suggestion is highly welcomed, if you have codes to put, I will test it.

    The scenerao is:
    create a randomAccessfile
    write 100 blank records( for future use)
    open this file
    write data to the records inside file
    close the file.
    I will try to put a testing code for you later on.

  • Random access file in process visability

    I want to use a file in a single process with single writer or multi readers mutual exclusion, for that purpose I use number of RandomAccessFile instances over the same file which are open in read mode and are used concurrently. I also have a single RandomAccessFile open in "rw" mode which updates the file (not when it is being actively read).
    I do not close the Random Access File handles at any point.
    I wanted to know if the data which is being written to the file with the RandomAccessFile in rw mode will always be visible to the readers after the the write is complete?
    (I am not using rws mode for performance issues, only for these readers which are in the same process).
    Thanks
    Eitan

    Looking at FileChannel it has the following part in its documentation:
    * The view of a file provided by an instance of this class is guaranteed
    * to be consistent with other views of the same file provided by other
    * instances in the same program. The view provided by an instance of this
    * class may or may not, however, be consistent with the views seen by other
    * concurrently-running programs due to caching performed by the underlying
    * operating system and delays induced by network-filesystem protocols. This
    * is true regardless of the language in which these other programs are
    * written, and whether they are running on the same machine or on some other
    * machine. The exact nature of any such inconsistencies are system-dependent
    * and are therefore unspecified.
    This looks exactly like the guarantee I need, now I've looked into RandomAccessFile.getChannel() implementation and it holds a single member of FileChannel which is initialized on demand and the next calls will return the same instance.
    So the only way I see to create multiple FileChannel instances over the same file is to open multiple RandomAccessFile instances over that file and use getChannel() on each of these instances. Since FileChannel does provide this guarantee I tend to believe it relies upon a guarantee that RandomAccessFile provide, otherwise it would need some mechanism to identify that different FileChannel instances over different RandomAccessFile instances are actually over the same file in order to provide the specified guarantee.
    What do you think?

  • Serialize tree in random access file

    I have a tree of objects, which are to be serialized. After deserialization,
    each object has to know its children and its parent. Each object need not know its sibling. There are no lateral references. The number of objects in the tree will be around 2000. The depth of tree is 7. Different parts of the tree will be saved and read at different points of time in the application. While the application is running, many of the objects in the tree keep undergoing changes which have to be saved intermittantly.
    I would like to use a random access file. But I have no clue how to serialize a tree of objects in a random access file which will meet the above mentioned requirements.
    I would be thankful if I could get an idea to implement.

    I have a tree of objects, which are to be serialized.
    After deserialization,
    each object has to know its children and its parent.
    Each object need not know its sibling. There are no
    lateral references. The number of objects in the tree
    will be around 2000. The depth of tree is 7.
    Different parts of the tree will be saved and read at
    different points of time in the application. This is an issue. When you Serialize something you serialize the entire object, not a part of it. If you're doing this then you're no longer talking about Serializing a Tree, you're talking about serializing some other thing that represents part of the tree.
    While
    the application is running, many of the objects in
    the tree keep undergoing changes which have to be
    saved intermittantly.
    I would like to use a random access file. But I have
    no clue how to serialize a tree of objects in a
    random access file which will meet the above
    mentioned requirements.
    I would be thankful if I could get an idea to
    implement.If you can come up with a "savable" representation of your tree that allows you to calculate where, in a file, a given part would be then you could use RandomAccessFile to read/write the thing. Just walk through your tree and seek to where you need to go in the file, then read/write the node.
    I hope that made sense
    Lee

  • Random access file in a midlet

    Hi, I'm trying to develop a small dictionary for MIDP2.0/CLDC1.0, so I need to random access a data file in an efficient way. MIDP API itself only provides a sequential access input stream. What is the best way for me to implement a file input stream that supports random access? Thanks a lot!

    Hi!
    There's nothing like RandmAccessFile in midlets, but there is a way, you can read (only!) a file from jar.
    Here's the code:
    InputStream is = this.getClass().getResourceAsStream("<path_to_the_file>");
    DataInputStream dis = new DataInputStream(is);Then you can read the stream with any of the metods provided.

  • How to change the file pointer in random access file?

    I have a file, now I want to add a line at both the beginning and ending of the file. Should I use random access in this case? How can I move the pointer to the end of the file in that case? Thanks!
    ruuram

    I have a file, now I want to add a line at both the
    beginning and ending of the file. Should I use random
    access in this case?That's up to you. RandomAccessFile doesn't allow you to insert data at the beginning of the file, though.
    How can I move the pointer to the
    end of the file in that case? Thanks!
    file.seek(file.length())

  • Error writing data in a flat file using UTL_FILE feature

    Hi All,
    I have written a package which fetches data from four different cursors and inserts into a temporary table.
    Now this temporary table is used to write data in a file using the UTL_FILE feature.
    fhandler :=
    UTL_FILE.fopen (l_path,'Demand_Transactions_'
    || TO_CHAR (SYSDATE, 'YYYYMMDDHH24MI')
    || '.txt',
    'w',
    max_linesize => 32767
    This table has 62593 records and when it starts writing data into the file from the table it errors out after writing 30045 records with the error - ORA-01722: invalid number.
    Can anyome please advise me is it because of the max_linesize => 32767. If not then what can be the possible reason.
    Any help in this would be highly appreciated.
    Regards,
    Shruti

    891330 wrote:
    Hi All,
    I have written a package which fetches data from four different cursors and inserts into a temporary table.
    Now this temporary table is used to write data in a file using the UTL_FILE feature.
    fhandler :=
    UTL_FILE.fopen (l_path,'Demand_Transactions_'
    || TO_CHAR (SYSDATE, 'YYYYMMDDHH24MI')
    || '.txt',
    'w',
    max_linesize => 32767
    This table has 62593 records and when it starts writing data into the file from the table it errors out after writing 30045 records with the error - ORA-01722: invalid number.
    Can anyome please advise me is it because of the max_linesize => 32767. If not then what can be the possible reason.Max linesize is the number of characters in a line before a newline has to be issued, not the number of rows written.
    The error would indicate that you have a character to number conversion going on somewhere but the characters are not numeric so it's failing that conversion.
    This doesn't sound like a UTL_FILE issue, but more to do with how you are building up your strings to output to the file.
    You would need to show us your code that builds up the lines you are writing out, with details of the datatypes of any of the columns/variables included in that.

  • Time Stamp problem while writing data into the excel file

    Hii, All
                  I am taking the data from the DAQ card of the TOPSCCC with the 8 ms of scanrate for each channel and there are total 16 no of Analog channels in the Card, now i am acquiring the data from the card, time stamping it and writing it into the excel file, which is tab delimited, now the problem is, the data which are in the excel file have the same timestamp for 4 to 5 continuous records, instead we want each data with the different and continuous time stamp with same difference of time stamp between two records, mean if it is difference of 8 ms then it should be the 8 ms for all, but here it is taking the differnce of 16 ms for two samples and giving same time stamp for four to five records and that shouldn't happen, here i am attaching my vi, drivers for the cards and Excel file with the data, can you please give me any suggestion how to do it?
           Please help me i require this suggestion as early as possible, i am requiring it urgently.
    Thanks in Advance,
    Nishant
    Attachments:
    2026vi.llb ‏319 KB
    2026_ScanMultAD_Demo_time.vi ‏80 KB
    Data.xls ‏357 KB

    Hello Nishant,
    that's what I meant:
    Message Edited by GerdW on 05-16-2006 10:32 AM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    timestamp-array.png ‏2 KB

  • Writing data from array to file

    May i know how to write string from a array into a file.
    I have use string tokenizer to extract every line from a file using readline and use stringtokenizer to spilt the line using tab delimiter for processing.
    But if i want to write data from array to file with tab as a delimiter and how to go to the next line. How do i do that. Below is the task and i have state a simple example on a array i have and the file output that i want.
    Pls advice.. Thanks
    eg of a array
    array[0] = Data
    array[1] = One
    array[2] = Data
    array[3] = Two
    array[4] = Final
    array[5] = Data
    From the above array, i want to write to a file so that it will appear something as below
    Eg textfile.txt
    Data One
    Data Two
    Final Data
    PLs attached a simple code as a example as i am only begining to start useing the IO feature in java. Thanks

    Really thanks for your help,
    but u are mentioning that i have already know the number of countters in advance , that is to say the 2 * counters.
    But is there a way to solve this problem which i mean if i dun know the number of predefined counters. Maybe i should say, there is more than 2 counters and in another situation, the counters will only be defined during runtime. Actually the solution u give will work nicely with 2 counters. but wat if the counter is more than 4, i wll have to concatenate the string a lot of time. so is there any solution around this problem. That why i am wandering if tere is any solution to write to the file when the counters can be only determined in runtime
    Pls advice on the above with a code samples if possible.

  • Writing data to a text file in a java code

    hey,
    can anybody tell me how can i enter data into a text file using java code.
    thanx

    yeah this is the proper answer....
    i had also a pblm ..that i had to read data from an excel sheet and write it to a File thru java code ....
    u can also use FileOutPutStream object....if u want...
    but there u can give newLine()..so all ur output will be in a single line to the file....
    bufferWriter.write(stringToBeWritten);
    bufferWriter.newLine();
    the stringToBeWritten can be a hardCoded string value..or any dynamic value like say fetching from database...

Maybe you are looking for

  • Help! I can't load images to craigslist.

    I am trying to post pictures of things to craigslist.  I select "picture library" from drop down menu and then it disappears... help?

  • Application Deployed other environment problem updating record

    Hi All, I have created a application in my working environment .Now when i want to deployed it to other environment everything goes fine except the updation is not working properly.I have add new and edit option in my application.When after editing a

  • NMH 410 "Remote Access" - Videos Do Not Play

    When accessing my Media Hub from a "remote" location the videos do not play (I only have videos on my Media Hub).  Instead, I get the following error message: Error: Could not play the selected title Windows Media: this media player was detected but

  • PR05 user-exit/badi to po-up

    Hi When I click on a row/travel expense of transaction PR05 I need a pop-up that warns if was set the number of miles (field KMGES) for that travel expense. Is there a user-exit/BADI to do it ? Any assistance would be greatly appreciated. Eric.

  • IPod won't recognize on my new computer

    I got a new computer I installed Ipod software cd and iTunes and I can't get my Ipod to show up with my music on iTunes or in Windows. Any suggestions?