ZipFile class random access

Hi All,
I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
Thanks

I want to implement this reading process using the RandomAccessFile and read the data randomly.You cannot do this directly on zipped data.
You could simulate random access by skipping over parts of the stream.
Or you could extract the data.

Similar Messages

  • Java ZipFIle Random access

    Hi All,
    I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
    Thanks

    I beg your pardon, I did not catch the idea. Why use a ZipFile to access ascii (i.e. text??) file?

  • ZipFile random access

    Hi All,
    I am using the ZipFile class in Java to parse/read data from an ascii file. But I want to implement this reading process using the RandomAccessFile and read the data randomly. But I am using a StreamTokenizer from the ZipFile to read the data currently, but I am stuck without knowing how to extend StreamTokenizer on the ZipFile to read the files randomly. Could anybody help me with this? Anyform of literature reference would be very helpful.
    Thanks

    I don't believe that is going to be possible, as the RandomAccessFile class is designed to work only with a file.
    You could extract the data from the zip file, write it to a new flat file, and then use RAF on that.

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

  • Please Come IN! IanSchneider. About random access serialized objects.

    Hi,I'm a freshman.
    I have a question about serialized objects.
    If I useing writeObject() serialize objects into a file in order,I can gain them with readObject() in the same order. But if I want to random access these serialized objects rather than one by one,how to do?
    Mr IanSchneider said "write all your objects into the same file using normal io techniques and you can still generate an index and acheive random access". It seems easy,but how to generate index and use it to acheive random access? Please write something in detail,Thank you in advance!
    EXPECTING��

    Have a look at this class: [ [u]WARNING: I just wrote this code, it hasn't been tested ]
    import java.io.BufferedInputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.RandomAccessFile;
    import java.io.Serializable;
    import java.util.ArrayList;
    public class SerializedObjectWriter {
         private RandomAccessFile raf;
         private String filepath;
         private String mode;
         public SerializedObjectWriter(String filePath, String mode) throws FileNotFoundException {                         
              this.filepath = filePath;
              this.mode = mode;
              this.raf = new RandomAccessFile(filePath, mode);                         
         public void writeObject(Object o, long pos) throws IOException {
              raf.seek(pos);          
              final byte[] bytes = serialize((Serializable)o);     
              raf.writeInt(bytes.length);     
              raf.write(bytes);
         public void append(Object o) throws IOException {                    
              writeObject(o, raf.length());
         public Object readObject(long pos) throws IOException, ClassNotFoundException {
              raf.seek(pos);
              int len = raf.readInt();          
              final byte[] data = new byte[len];          
              raf.readFully(data);
              return deSerialize(data);
         public Object[] readAllObjects() throws IOException, ClassNotFoundException {          
              int pos = 0;          
              final ArrayList al = new ArrayList();
              while (true) {
                   raf.seek(pos);
                   final int len = raf.readInt();               
                   final byte[] data = new byte[len];          
                   raf.readFully(data);
                   al.add(deSerialize(data));
                   pos = (pos + len + 4);               
                   if (pos >= raf.length()) break;               
              return al.toArray();
         public long length() throws IOException {
              return raf.length();
         public void reset() throws IOException {          
              raf.close();
              final boolean success = new File(filepath).delete();
              if (!success) throw new IOException("Failed to delete file");
              raf = new RandomAccessFile(filepath, mode);
         public void close() throws IOException {          
              raf.close();     
         private byte[] serialize(Serializable obj) throws IOException {
              final ByteArrayOutputStream baos = new ByteArrayOutputStream();
              final ObjectOutputStream oos = new ObjectOutputStream(baos);
              try {
                   oos.writeObject(obj);
              } finally {
                   oos.close();
              return baos.toByteArray();
         private Object deSerialize(byte[] data) throws IOException, ClassNotFoundException {
              final ByteArrayInputStream bais = new ByteArrayInputStream(data);     
              final BufferedInputStream bis = new BufferedInputStream(bais);
              final ObjectInputStream ois = new ObjectInputStream(bis);
              try {
                   return (Serializable) ois.readObject();               
              } finally {
                   ois.close();
         public static void main(String[] args) throws Exception {
              SerializedObjectWriter sor = new SerializedObjectWriter("C:\\test.ser", "rw");          
              sor.reset();
              sor.writeObject("Test 1", 0);                         
              sor.append("Test 2");               
              sor.append("Test 3");     
              Object[] objects = sor.readAllObjects();
              for (int i = 0; i < objects.length; i++) {
                   System.out.println(objects);
              sor.close();

  • 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

  • Why do I need to define these in std for my random access iterator???

    Hi guys,
    I have written my own iterator class, to support 1-d slices of 2-d matrices, 2-d slices of 3-d matrices, etc.
    At first I wrote the class as a bidirectional iterator, but then I needed to extend it to random access so that I could pass these iterators to std::sort etc. No problem, I thought, I just needed to add friend operators for "iterator-iterator" and "iterator+/-distance".
    So, I did that and tested the code with VS6 and various versions of g++, with no problems. Isn't STL great!
    But I had endless problems with Studio 10. It kept griping that various mostly-internal-looking template functions were not defined. The only way I could get it to work was to define these:
    #if (defined __SUNPRO_CC) && (__SUNPRO_CC <= 0x570)
    namespace std
         template<typename T>          // Sigh
         typename matrixit<T>::
         difference_type distance(const matrixit<T>& a, const matrixit<T>& b) {
              return b-a;
         template<typename T>           // WTF?
         T* __value_type(const matrixit<T>&) {
              return static_cast<T*>(0);
         template<typename T>           // WTF?
         typename matrixit<T>::
         difference_type* __distance_type(const matrixit<T>&) {
              return static_cast<typename matrixit<T>::difference_type*>(0);
         template<typename T>           // WTF?
         typename matrixit<T>::
         iterator_category __iterator_category(const matrixit<T>&) {
              return typename matrixit<T>::iterator_category();
    #endif
    Why do I have to do this, or am I missing something in my iterator class (eg, typedefs), or do I need to derive it from something? Here is what it looks like:
    template<typename T>
    class matrixit
    public:
         typedef T&                         reference;
         typedef T*                         pointer;
         typedef T                         value_type;
         typedef size_t                    size_type;
         typedef ptrdiff_t               difference_type;
         typedef std::random_access_iterator_tag iterator_category;
    Ta, Simon.

    Come on, it is not that hard to work around the limitations of Cstd. For what you show here, you can use:
    namespace std {
    template <class Iterator> struct iterator_traits
    typedef typename Iterator::value_type value_type;
    typedef typename Iterator::difference_type difference_type;
    typedef typename Iterator::pointer pointer;
    typedef typename Iterator::reference reference;
    typedef typename Iterator::iterator_category iterator_category;
    template <class T> struct iterator_traits<T*>
    typedef T value_type;
    typedef ptrdiff_t difference_type;
    typedef T* pointer;
    typedef T& reference;
    typedef random_access_iterator_tag iterator_category;
    template <class T> struct iterator_traits<const T*>
    typedef T value_type;
    typedef ptrdiff_t difference_type;
    typedef const T* pointer;
    typedef const T& reference;
    typedef random_access_iterator_tag iterator_category;
    template <class ForwardIterator>
    inline ptrdiff_t
    distance (ForwardIterator first, ForwardIterator last)
    ptrdiff_t n = 0;
    __distance(first, last, n,
    iterator_traits<ForwardIterator>::iterator_category());
    return n;
    template <class InputIterator, class T>
    inline typename iterator_traits<InputIterator>::difference_type
    count (InputIterator first, InputIterator last, const T& value)
    typename iterator_traits<InputIterator>::difference_type result;
    count(first,last,value,result);
    return result;
    template <class InputIterator, class Predicate>
    inline typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, Predicate pred)
    typename iterator_traits<InputIterator>::difference_type result;
    count_if(first,last,pred,result);
    return result;
    template < class T >
    inline typename T::value_type*
    __value_type (const T&)
    { return (typename T::value_type*)(0); }
    template < class T >
    inline typename T::difference_type*
    __distance_type(const T&)
    { return (typename T::difference_type*)(0); }
    template < class T >
    inline typename T::iterator_category
    __iterator_category (const T&)
    typename T::iterator_category tmp;
    return tmp;
    } // namespace std
    For the missing constructor of vector with iterators, you can simply use std::copy with a back_insert_iterator.
    The hardest thing to work around is probably the missing conversion between std::pair of various types (for instance with various constness when you use std::map), but it can still be handled by always specifying the type of the pair instead of relying on std::make_pair.
    And if there is a thing you really don't know how to work around, you can always ask here...

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

  • Random results with  random access query

    Hi,
    when I execute a random access query
    (fetchConfig.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
    fetchConfig.setFetchDirection(ResultSet.FETCH_UNKNOWN)) and iterate over the
    result set twice, the second time the objects are retrieved in a different
    order, also when I set the ordering of the objects. This only happens if the
    first loop touches the last item. If not, everything works fine. I am using
    MS Sql Server, microsoft driver, kodo 3.4
    regards,
    Christiaan

    Hi,
    I am using datastore identity. I do implement equals and hashcode in the
    super class, not sure whether that is of any impact. The order of the items
    look random to me, however it stays constant after the second loop. The same
    order is also produced when I re-start the test application. The output
    shows the index of the object I am retrieving, the description of the object
    (which is also the order in which the items are created) and their order
    attribute. The query sorts on the order attribute. As you can see the first
    loop is correct. I now and then have the situation where the last item in
    the first loop (retrieve 7) results in the first item (item nr 0) being
    retrieved. Same behaviour applies for both jtds and microsoft driver.
    first loop:
    retrieve 0: item nr: 0 order: 0
    retrieve 1: item nr: 1 order: 1
    retrieve 2: item nr: 2 order: 2
    retrieve 3: item nr: 3 order: 3
    retrieve 4: item nr: 4 order: 4
    retrieve 5: item nr: 5 order: 5
    retrieve 6: item nr: 6 order: 6
    retrieve 7: item nr: 7 order: 7
    second loop
    retrieve 0: item nr: 3 order: 3
    retrieve 1: item nr: 6 order: 6
    retrieve 2: item nr: 7 order: 7
    retrieve 3: item nr: 0 order: 0
    retrieve 4: item nr: 5 order: 5
    retrieve 5: item nr: 4 order: 4
    retrieve 6: item nr: 2 order: 2
    retrieve 7: item nr: 1 order: 1
    third loop
    retrieve 0: item nr: 3 order: 3
    retrieve 1: item nr: 6 order: 6
    retrieve 2: item nr: 7 order: 7
    retrieve 3: item nr: 0 order: 0
    retrieve 4: item nr: 5 order: 5
    retrieve 5: item nr: 4 order: 4
    retrieve 6: item nr: 2 order: 2
    retrieve 7: item nr: 1 order: 1
    "Marc Prud'hommeaux" <[email protected]> wrote in message
    news:[email protected]...
    Christiaan-
    My first guess is are you using application identity, and if so, are you
    correctly implementing the equals() and hashCode() method? Failure to do
    so may conceivably cause this problem.
    Otherwise, can you provide some details about how the results are our of
    order? It it exactly reverse or something, or are elements in random
    order?
    Christiaan wrote:
    Hi,
    when I execute a random access query
    (fetchConfig.setResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE);
    fetchConfig.setFetchDirection(ResultSet.FETCH_UNKNOWN)) and iterate over
    the result set twice, the second time the objects are retrieved in a
    different order, also when I set the ordering of the objects. This only
    happens if the first loop touches the last item. If not, everything works
    fine. I am using MS Sql Server, microsoft driver, kodo 3.4
    regards,
    Christiaan
    Marc Prud'hommeaux
    SolarMetric Inc.

  • A Random access Set

    any ideas about how to create a random access set? It'd be nice to have a class that implements a Set and a List.
    How would you do something like this? I read somewhere in the API docs that you wouldn't be able to over-ride equals properly or something?

    The equals method for Set is the usual definition of Set-equality: a Set can only equal another Set, and then only when they have the same size and exactly the same members. A List can only equal another List, and then only when they have the same size and the same sequence of members. So an object can't have both types.
    On the other hand, nothing stops a Set from having a random-access operation like get(). Just document that equal Sets may return differenet elements: after all, iterators provided by equal Sets don't have to provide the same sequence of members.
    --Nax

  • Weird classpath issue in EAR.Some classes can access jars that others cant!

    Hi,
    I'm experiencing a very frustrating problem that's proving to be a bit of a show stopper for me. I would really appreciate some help...
    I have an EAR deployed successfully on Sun Appserver 8 which passes the tests from the sun EAR verifier tool. The ear contains a jar file that I built which has a stateless session bean, home, remote interfaces and rmi stubs, deployment descriptors, as well as some utility classes. The EAR also contains some third-party jars such as Hibernate, Log4-j, apache-commons etc etc. The jar I built has in it's manifest file, the classpath information to reference the other jars in the ear.
    The problem I am having is that one of the classes in a third-party jar (hibernate3.jar) cannot see a class in another of the third party jars (log4j-1.2.8.jar) and as a result is throwing a NoClassDefFoundError for org/apache/log4j/Layout while trying to initialise - the two jars are at the root of the EAR.
    Furthermore, my utility classes can access and use Log4j classes without any problem and logging command from those classes is output successfully to the server console. However, my session bean, which is packaged in the same jar as the utility classes, fails to log anything even though it uses exactly the same logger and log configuration as the utility classses.
    I have tried adding classpath information to the manifest of the EAR so that the third-party jars can pick it up but this makes no difference. Also, according to the EAR verifier tool, you are not allowed to put any classpath information in the EAR manifest.
    I have also tried deploying this in weblogic but am experiencing the same problem.
    If anyone can offer any advice or solutions I would greatly appreciate it.
    :)

    what´s type error have you?
    perhaps external libraries (located in classpath) invoke opsCommon.jar and config-3.0.jar classes. then, classnotfound is normal.
    and... why separate external libraries (opsCommon.jar and config-3.0.jar inside ear, and other in classpath)?

  • Seagate Barracuda ES ST3750640NS 750 GB - slow random access in MacPro

    I installed four Seagate Barracuda ES ST3750640NS 750 GB disks in my MacPro (5GB RAM). They are mounted as two RAID-1 arrays (mirrored, no speed up).
    It seems that also those (not just the non-ES, …AS version) suffers from slow speeds (<1MB) in random access with small blocks. How much this is representative of typical access with Mac OS X I cannot tell, but still this looks like some kind of incompatibility of the drives' firmware with a MacPro.
    Does anyone have experience on how to correct that?
    Xbench 1.3 results:
    Disk Test 35.16
    Sequential 93.74
    Uncached Write 83.37 51.19 MB/sec [4K blocks]
    Uncached Write 120.10 67.95 MB/sec [256K blocks]
    Uncached Read 73.82 21.60 MB/sec [4K blocks]
    Uncached Read 113.60 57.09 MB/sec [256K blocks]
    Random 21.64
    Uncached Write 6.46 0.68 MB/sec [4K blocks]
    Uncached Write 88.67 28.39 MB/sec [256K blocks]
    Uncached Read 85.41 0.61 MB/sec [4K blocks]
    Uncached Read 140.90 26.14 MB/sec [256K blocks]
    12" PB G4/1.2GHz- Mac Book Pro 17" - 12" iB G3/500 MHz - Mac mini G4 as server   Mac OS X (10.4.8)  

    All of the Seagate 7200.10 model hard drives have slow Random Read performance. None of the different model numbers change this fact. There is no fix for this and you will probably only notice this issue when opening a large library with Aperture or some other application that depends on a large number of small files to read.
    The Randowm write performance of the Seagate 7200.10 models is actually very good. In addition, the large block copy capabilities of the 7200.10 models is exceptional.
    Xbench tests make the Seagate 7200.10 model performance look much worse than it actually is.

  • CSV vhdx files and SAN optimization - sequential or random access or...?

    Is there a best practice on the SAN optimization of LUNs for CSV VHDX files - e.g. sequential vs. random access?
    We recently set up a small two-node Hyper-V 2012 R2 Failover Cluster. As I was creating LUNs for the CSV vhdx files, our SAN (like most, I think) has some pre-set optimization options which are more or less sequential vs. random access. There's now the abstraction
    layer of shared VHDX files and the actual data those VHDXs are being used to store.  Are there any best-practices for SAN optimization in this regard?
    In other words, I could see:
    A. Cluster-shared VHDXs are accessed (more-or-less) based on the type of data they're used for
    B. All cluster-shared VHDXs are (more-or-less) accessed sequentially
    C. All cluster-shared VHDXs are (more-or-less) accessed randomly.
    I have one source that says that for a relatively simple SMB setup like we have that "C" is the recommendation.  I'm curious if anyone else has run into this or seen an official best-practice...?

    Is there a best practice on the SAN optimization of LUNs for CSV VHDX files - e.g. sequential vs. random access?
    We recently set up a small two-node Hyper-V 2012 R2 Failover Cluster. As I was creating LUNs for the CSV vhdx files, our SAN (like most, I think) has some pre-set optimization options which are more or less sequential vs. random access. There's now the abstraction
    layer of shared VHDX files and the actual data those VHDXs are being used to store.  Are there any best-practices for SAN optimization in this regard?
    In other words, I could see:
    A. Cluster-shared VHDXs are accessed (more-or-less) based on the type of data they're used for
    B. All cluster-shared VHDXs are (more-or-less) accessed sequentially
    C. All cluster-shared VHDXs are (more-or-less) accessed randomly.
    I have one source that says that for a relatively simple SMB setup like we have that "C" is the recommendation.  I'm curious if anyone else has run into this or seen an official best-practice...?
    There as good article published recently by Jose Barreto about CSV performance counters. See:
    Cluster Shared Volume: Performance Counters
    http://blogs.msdn.com/b/clustering/archive/2014/06/05/10531462.aspx
    You can run DiskSPD or Intel I/O Meter yourself to see what workload you'll get @ CSV with 10+ VMs doing different I/O types. We did and you'll get
    4-8KB 100% random reads and writes (just make sure you gather statistics for a long time).
    So that's type of workload you could optimize your LUN @ SAN level.
    StarWind Virtual SAN clusters Hyper-V without SAS, Fibre Channel, SMB 3.0 or iSCSI, uses Ethernet to mirror internally mounted SATA disks between hosts.

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

Maybe you are looking for

  • Problem in WEB-UI field (Not Bound)

    Hi Experts,    I am new to CRM Technical, I have added new standard field (Date Of Birth) thourgh component work bench 'BSP_WD_CMPWB'  in 'Z_IC_AGENT' business role. after execution this business roles i could able to see this DOB field but its showi

  • How to restart iphone 4s

    Hi! I've got a new iphone 4s and would like to restore from icloud, but it's been already set up. I mean i don't have that welcome thing anymore, where it asks if i want to restore from icloud. How do i go back to that status or is there any other wa

  • Problem saving data model when using Oracle DB Pivot feature

    I have problem saving a data model - SQL Query that uses the Oracle DB PIVOT feature? When I hit save, nothing happends.... have also tried "save as" - nothing is saved No error message is shown. Is Oracle DB PIVOT not supported by OBIEE? The SQL tha

  • Stretching the whole timeline in Motion 2

    Hi guys, I was or am working on a project which is almost finished but the movie needs to be a little bit slower. I already read that there is no real possibility to enlarge the whole timeline - just via the scrubbing filter. Is there no other way to

  • Image accesibility

    I have a sequence of images that appear and then fade through out a slide. Other than describing them in the properties within the narration script (description) as they come up, is there another option? Am I 508 compliant doing it this way? I am use