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.

Similar Messages

  • Can I produce such a result with a single query?

    I am having a table with records like
    A....B
    1....20
    2....19
    3....03
    4....09
    5....74
    6....24
    7....31
    Column A is a primary key and Column B has radomly generated positive integer numbers. I need to generate one more column C with randomly generated positive integer values (including 0) so that -
    1) The values genereated for the Column C must be less than or equal to corresponding value of Column B.
    2). The randomly generated values for Column C should be in such a way so that the sum of values for Column C would be 30% of the sum of values of Column B.
    In our example, the sum(B) = 180. So the sum(C) should be around 54.
    One of the snap of column C can be like this...
    A....B....C
    1....20....14
    2....19....00
    3....03....02
    4....09....03
    5....74....03
    6....24....01
    7....31....31
    ......==-..==
    .....180...54
    How do I write a query to produce such a result?

    You may try the following:
    SQL> CREATE TABLE t AS SELECT ROWNUM a,ROUND(DBMS_RANDOM.VALUE(10,99)) b FROM user_objects WHERE ROWNUM <= 15
    Table created.
    SQL> BREAK on l
    SQL> COMPUTE SUM OF b on l
    SQL> COMPUTE SUM OF c on l
    SQL> SELECT a,
           b,
           c,
           l
      FROM (SELECT a,
                   b,
                   c,
                   ROUND (30 / 100 * s) s,
                   SUM (c) OVER (PARTITION BY l) d,
                   l
              FROM (SELECT a,
                           b,
                           l,
                           ROUND (DBMS_RANDOM.VALUE (1, b)) c,
                           SUM (b) OVER (PARTITION BY l) s
                      FROM t,
                           (SELECT     LEVEL l
                                  FROM DUAL
                            CONNECT BY LEVEL <= 50000)))
    WHERE d = s
             A          B          C          L
             1         12          3        184
             2         40         31          
             3         79          7          
             4         46          8          
             5         18          7          
             6         14          3          
             7         48         12          
             8         32          8          
             9         67         16          
            10         25         20          
            11         23         17          
            12         22          2          
            13         24          8          
            14         74          5          
            15         48         25          
                      572        172 sum      
             1         12          3      10298
             2         40         25          
             3         79         32          
             4         46          6          
             5         18          6          
             6         14          4          
             7         48          4          
             8         32         26          
             9         67         31          
            10         25          2          
            11         23          3          
            12         22         12          
            13         24          7          
            14         74          3          
            15         48          8          
                      572        172 sum      
             1         12          8      13450
             2         40          5          
             3         79         12          
             4         46         13          
             5         18         11          
             6         14         11          
             7         48          8          
             8         32         22          
             9         67          3          
            10         25          4          
            11         23          2          
            12         22         14          
            13         24         12          
            14         74         40          
            15         48          7          
                      572        172 sum      
             1         12          1      16656
             2         40         31          
             3         79          3          
             4         46         20          
             5         18          9          
             6         14          5          
             7         48         18          
             8         32         24          
             9         67         16          
            10         25          5          
            11         23          7          
            12         22          2          
            13         24          6          
            14         74         23          
            15         48          2          
                      572        172 sum      
             1         12          5      19842
             2         40         11          
             3         79         11          
             4         46         12          
             5         18          2          
             6         14          2          
             7         48          3          
             8         32         16          
             9         67         10          
            10         25         11          
            11         23         17          
            12         22         18          
            13         24          6          
            14         74         26          
            15         48         22          
                      572        172 sum      
             1         12          3      22337
             2         40         18          
             3         79          9          
             4         46         26          
             5         18         11          
             6         14          9          
             7         48         25          
             8         32         14          
             9         67          6          
            10         25          3          
            11         23         21          
            12         22         12          
            13         24         10          
            14         74          4          
            15         48          1          
                      572        172 sum      
             1         12          5      24501
             2         40         11          
             3         79         48          
             4         46          3          
             5         18          6          
             6         14          8          
             7         48          2          
             8         32          3          
             9         67         21          
            10         25          7          
            11         23         16          
            12         22          2          
            13         24         16          
            14         74         12          
            15         48         12          
                      572        172 sum      
             1         12          8      24555
             2         40         29          
             3         79          7          
             4         46         13          
             5         18          5          
             6         14          4          
             7         48         20          
             8         32          3          
             9         67         17          
            10         25         13          
            11         23         18          
            12         22          2          
            13         24          5          
            14         74         27          
            15         48          1          
                      572        172 sum      
             1         12          7      27312
             2         40         11          
             3         79          3          
             4         46         37          
             5         18          3          
             6         14          7          
             7         48         16          
             8         32          8          
             9         67         27          
            10         25          2          
            11         23         14          
            12         22          4          
            13         24         20          
            14         74          9          
            15         48          4          
                      572        172 sum      
             1         12          3      29197
             2         40         12          
             3         79         24          
             4         46         17          
             5         18          6          
             6         14          9          
             7         48         17          
             8         32         17          
             9         67          4          
            10         25         23          
            11         23         15          
            12         22          4          
            13         24          5          
            14         74          2          
            15         48         14          
                      572        172 sum      
             1         12          8      32635
             2         40          5          
             3         79         21          
             4         46          1          
             5         18          9          
             6         14          6          
             7         48         20          
             8         32          6          
             9         67         43          
            10         25         10          
            11         23         15          
            12         22          5          
            13         24          4          
            14         74         15          
            15         48          4          
                      572        172 sum      
             1         12          2      38404
             2         40         26          
             3         79          6          
             4         46         28          
             5         18          4          
             6         14          2          
             7         48          4          
             8         32         13          
             9         67         19          
            10         25          3          
            11         23          3          
            12         22         11          
            13         24         13          
            14         74         32          
            15         48          6          
                      572        172 sum      
             1         12         10      38830
             2         40          5          
             3         79          8          
             4         46          3          
             5         18          2          
             6         14         12          
             7         48         42          
             8         32          5          
             9         67         27          
            10         25          4          
            11         23          9          
            12         22         11          
            13         24         11          
            14         74         10          
            15         48         13          
                      572        172 sum      
             1         12          2      42291
             2         40          5          
             3         79         34          
             4         46         24          
             5         18         15          
             6         14          7          
             7         48          7          
             8         32         10          
             9         67          1          
            10         25          5          
            11         23         20          
            12         22          8          
            13         24          3          
            14         74          7          
            15         48         24          
                      572        172 sum      
             1         12          5      47614
             2         40          6          
             3         79         15          
             4         46         32          
             5         18          6          
             6         14         12          
             7         48          8          
             8         32          7          
             9         67          6          
            10         25         22          
            11         23          8          
            12         22          3          
            13         24         17          
            14         74         13          
            15         48         12          
                      572        172 sum      
    225 rows selected.

  • How can I share the results with limited access to another user

    I am adding another user to be able to see results of forms submitted, I want the user to add some text into the results view but I don't want him to have access the the design view. How can I make that happen?

    Karina Wiggs
    Director of Operations
    Community Lodgings
    Office: (703) 549-4407
    Cell: (301) 412-4407
    Fax: (703) 548-1294
    Facebook <https://www.facebook.com/Community.Lodgings?ref=tn_tnmn> I
    Twitter  <https://twitter.com/CommunityLdgngs>I Instagram
    <http://instagram.com/communitylodgings>
    www.communitylodgings.org
    On Thu, Dec 4, 2014 at 11:43 AM, Vikrantt Singh <[email protected]>

  • Getting result with single query

    Hi,
    I'm using db 10.2.0.1.0
    I have a table emp_shift , with data like below
    EmpCode           Shift     Effdate            Default
    1                 SHFT1    02-jan-2012          N
    1                 SHFT2    04-jan-2012          Y
    1                 SHFT3    04-jan-2012          NSo if user inputs EmpCode and Effdate, based on that i've to take the latest record, with default = 'Y' (if any) else default 'N'
    Suppose
    Case 1 : Input Empcode:1 Date:10-jan-2012
    Then i should get the below record
    1                 SHFT2    04-jan-2012          YCase 2 : Input Empcode:1 Date:03-jan-2012
    Then i should get the below record
    1                 SHFT1    02-jan-2012          NI want this result with a single query, is this possible?
    Thanks
    Divya

    Hi Thank you both,
    I'm trying this process through forms. and my forms version is 6i.
    There where i'm trying the query with the cursor, i'm getting error
    Encountered the symbol Order when expecting one of the following
    .()...and my cursor is
    Cursor cur_shft(vemp Varchar2,vdate Varchar2) is Select ESM_SHIFT_TYPE
         from (Select ESM_SHIFT_TYPE from EMPLOYEE_SHIFT_MASTER
                   Where ESM_EMP_CODE = vemp
                   and ESM_EFF_DATE <= vdate
                   Order by ESM_EFF_DATE desc,Esm_Default desc)
                   Where rownum=1 ;Whats wrong?

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

  • Manipulating random access dat files

    I have a bit of a problem, i inherited a system written in qbasic and i need to be able to manipulate some .dat files which are stored as random access binary files.
    my input stream is as follows
    RandomAccessFile vansfile = new RandomAccessFile("c:\\vansfile.dat", "rw");
    no problems here. i then create a byte array of size record length which happens to be 2462 bytes long and read the first 2462 bytes to the array.
    byte[] sss = new byte[2462];
    int j j = vansfile.read(sss)
    now i know roughly at which offsets some data fields are kept, for instance bytes
    sss[0] and sss[1] = a label which is stored in ascii,and bytes 7 to 27 hold a persons name ie byte 7 holds 78 = N byte 8 holds 65 = A ... which ends up spelling NATASHA (the persons name). SO FAR SO GOOD
    NOW apparently bytes 1413 to 1420 holds a monetary value (which i assume is encoded as an integer or a double). if i print the byte values, i get the following where the number before the : is the byte and the number after the : is the value.
    1413 : -102
    1414 : -103
    1415 : -103
    1416 : -103
    1417 : -103
    1418 : -7
    1419 : -126
    1420 : 64
    NOW this Number is supposed to be 60720 ($607.20)
    does anyone know if there is any function which will interpret the above bytes correctly as the result (which i know is correct).

    Your data in bytes 1413 -1420 is stored in the IEEE 754 floating-point "double format" bit layout (the format Java uses for a double),
    and it has the value 607.2
    BUT - it was written in littleEndian, whereas Java uses bigEndian. Makes sense, since QBasic is a MS product, and MS uses littleEndian.
    You can either reverse the byte order and use Double.longBitsToDouble to create a java double, or read it with one of the methods that can read littleEndian.
    If you use the longBitsToDoublemethod, it needs a long as its argument. The easiest way to do that is to create a long using the hex values of the bytes. For example, using your data converted to hex:
    1420: 40
    1419: 82
    1418: f9
    1417: 99
    1416: 99
    1415: 99
    1414: 99
    1413: 9a
    long bits = 0x4082f9999999999aL;
    double d = Double.longBitsToDouble(bits);

  • Random Access

    Hi,
    When we say that the ArrayList is random access,what exactly do we mean by "Random Access"

    I was half tempted to start my post out with sigh like some of the regulars around here, but then I realized how annoying and stupid that is...
    Anyway, have you tried googling 'random access'? When I did, the fourth result was a fairly decent description of what random access means.
    From http://www.webopedia.com/TERM/R/random_access.html
    Refers to the ability to access data at random. The opposite of random access is sequential access. To go from point A to point Z in a sequential-access system, you must pass through all intervening points. In a random-access system, you can jump directly to point Z. Disks are random access media, whereas tapes are sequential access media.
    If you need the item at index 2 in an ArrayList, you can retrieve it directly. For a LinkedList, you would need to iterate though the list until you reach that element. The get(int) method of LinkedList simply does the iteration for you.

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

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

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

  • Xml elements random access table

    hi all,
    i'm having a random access table holdin the index for each xml node in a xml file, any idea how can u access the xml node directly without going through the whole xml file. i want to do this by either sax or stax, dom is not valid with my case. thanx

    eng_cs wrote:
    hi all,
    i'm having a random access table holdin the index for each xml node in a xml file, any idea how can u access the xml node directly without going through the whole xml file. i want to do this by either sax or stax, dom is not valid with my case. thanxI far as I know you could only accomplish such a thing using DOM parser alone, as DOM supports XPATH. SAX or StAX do not support XPATH, so directly going to the node in a xml is not possible using SAX or StAX.

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

  • Randomly accessing serialized objects

    Is there any way to access objects written to a file randomly. Serialization basically needs accessing objects in the same order as they are writeen. but i need to access object(s) in any order.
    Any suggestions on how to do so?

    I got this reply when i questioned the person
    incharge...may be theres much more to it than i
    could specify..........It could also be the case that the person in charge doesn't know that there are databases with small footprints implemented in java.
    so i would be glad if soemone
    could tell me what ever i plan to do with respect to
    random accessing is possible or not.....I think that you should be able to write all objects to one stream, and do a reset (on the object output stream) between each write, and write the start position of each object into an index file.
    I'm not sure that it will work, and having a data file + an index file is like having a small database (so why not download a database in that case)
    /Kaj

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

Maybe you are looking for