Determining end of file when file consists of objects

Hi
I'm having trouble working out how to determine end of file when the file consists of multiple objects
I've written multiple Person objects to an XML file and I can read the first back
public Vector<Person> readVectorFromFile() throws CJException {
         Vector<Person> v = new Vector<Person>();
         try {
         XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream("VectorStore.xml")));
         // while there are Persons remaining in the file
         Person p;
         //for each p in the file
         do {
             p = (Person) d.readObject();
             v.add(p);                      
         } while(// can't work out how to test this);
         d.close();
         catch(IOException ioe) {
             throw new CJException("Error reading file: " + ioe.getCause());
         }al the books either give examples with the reading of a single object or reading multiple charaters...i've tried testing when p is null and using int c but these give ArrayIndexOutOfBoundsExceptions at runtime.
Please could someone point me in the right direction?
Thanks

paulcw wrote:
Similarly, this sucks:
try {
int i = 0;
while(true)
System.out.println(someArray[i++]);
} catch (ArrayIndexOutOfBounds e) {
// ignore
True, but that is not the case in this instance, if that is what you're getting at. The problem is that the "read" method of this "Reader" throws an ArrayIndexOutOfBounds exception, without providing any way of figuring out if there is even anything to read. And that, in and of itself, is a remarkable event.
The only other ways I see to avoid are all cludge work-arounds or innefficient. You could have the first object in the file be an Integer to indicate the number of objects (but what if, then, for whatever reason, the Stream is "emtpy"). You could parse the XML stream counting the number of "object" elements then push it all back, or reset if the underlying stream supports one of those, or reopen the stream and parse it again (this time with the readObject method), all of which are highly ineffecient. You could transmit, beforehand, how many elements there are, or "define" that there will "always" be only so many elements, etc.
Everyone of those possible solutions (with the exception of the second, which is simply inneffecient) makes the entire thing rigid and inflexible, and, essentially, non-reusable.
The while (or whatever) loop and catch at least make it generally usuable in all situations. It is, I agree, less than optimal, but still the "best" option, in this particular instance.

Similar Messages

  • End of file error when running an extremely specific SQL call

    When I run the query below through my VB.NET app with certain table and column names as parameters on an Oracle 10.1 database (Connection.ServerVersion reports it as 10.1.0.4.0), it fails and throws the following error: Oracle.DataAccess.Client.OracleException: ORA-03113: end-of-file on communication channel. The query does not fail for most table/column names--only a few. The query does not fail with any set of parameters when I run it directly through PL/SQL Developer, nor does it fail with any set of parameters when I run it through VB against a 10.2 database. I'm using ODP.NET 10.2.0.2.20.
    Here's the SQL:
    SELECT search_condition check_constraint, cols.constraint_name
    FROM user_constraints cons, user_cons_columns cols
    WHERE constraint_type = 'C'
    AND cols.owner = cons.owner
    AND cols.table_name = cons.table_name
    AND cols.constraint_name = cons.constraint_name
    AND cols.table_name = UPPER(:tableName)
    AND cols.column_name = UPPER(:columnName)But the weirdest part is that the query always works if I make any one of these changes:
    *Change the WHERE line to: "WHERE cons.constraint_type = 'C'".
    *Get rid of the UPPERs and pass in upper-case parameters.
    *Remove one of the parameters
    *Remove "constraint_type = 'C'"
    *Change the last line to 'EXPECTED_VALUE' = UPPER(:columnName)
    Is there something special about the Query of Death that I wrote? Is anyone even able to replicate this error, iterating in VB over all the columns in a good-sized database? I've never seen anything like this before.
    Thanks in advance for your help,
    -Justin

    Hi Justin,
    I tried to reproduce your complaint, but wasnt able to. I didnt have a 10104 db to test against though, but I did test against 10105, and 10202, using the following dumb table:
    create table constr_test ( c1 number);
    alter table constr_test add constraint const_1 check (c1 in (1,2,null));
    insert into constr_test values (3);
    commit;
    Frequently a 3113 is the result of an ora-600 or ora-7445 on the database. The fact that it doesnt occur for you on 10.2 db leads me to believe that might be the case here. Have you checked your alert logs?
    Cheers,
    Greg

  • NT 4.0, LabVIEW 6, Error 4 (END OF FILE) when trying to seek to byte offset 4096 (from start of file) when the file is larger than 2 Gig

    If I try to seek (or read) with the position mode wired and set for START, I get error 4 (END OF FILE) if the file is larger than 2 GB. I'm only trying to move the file pointer 4096 bytes, not trying to seek or read more than 2GB, but I get the error if the file is over 2Gig.
    Instead, I have to do reads, with the position mode unwired, until I get to the place in the file that I want to be.
    Is this expected behavior?

    Hello,
    LabVIEW File I/O functions use an I32 value to store the size of a file. This means that we are limited to ~2GB file sizes when using the File I/O functions in LabVIEW. This explains why you are seeing odd behavior when trying to read to the end of the file, since this is causing the byte count to exceed ~2GB.
    I hope this explanation sheds some light on the situation for you. Hopefully the workaround (repeated reads) is not too much of an inconvenience.
    Good luck with your application, and have a pleasant day.
    Sincerely,
    Darren Nattinger
    Applications Engineer
    National Instruments
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman

  • Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    Hi folks,
    I am using a cascaded mapping in my OM. I have a graphical mapping followed by the Java mapping. It is a flat file to IDOC mapping. Everything works fine in Dev but when I transport the same objects to QA, the Operation mapping though it doesn't fail in ESR testing tool, gives the following message and there is no output generated for the same payload which is successfully tested in DEV. Please advise on what could be the possible reasons.
    Unable to display tree view; Error when parsing an XML document (Premature end of file.)

    kalyan,
    There seems to be an invalid xml payload which causes this error in ESR not generating the tree view. Please find the similar error screenshot and rectify the payload.
    Mutti

  • PLS-00103: Encountered the symbol "end-of-file" when expecting one of the f

    I'm trying to follow an example pl/sql program to select from one table and insert into a second table in a LOOP.
    I get a syntax error which I can't figure out
    Line # = 67 Column # = 0 Error Text = PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    pipe
    What is the cause?
    IS
    BEGIN
    declare
    v_pk1 bb_bb60_stats.pk1%TYPE;
    v_event_type bb_bb60_stats.event_type%TYPE;
    v_user_pk1 bb_bb60_stats.user_pk1%TYPE;
    v_course_pk1 bb_bb60_stats.course_pk1%TYPE;
    v_group_pk1 bb_bb60_stats.group_pk1%TYPE;
    v_forum_pk1 bb_bb60_stats.forum_pk1%TYPE;
    v_internal_handle bb_bb60_stats.internal_handle%TYPE;
    v_content_pk1 bb_bb60_stats.content_pk1%TYPE;
    v_data bb_bb60_stats.data%TYPE;
    v_timestamp bb_bb60_stats.timestamp%TYPE;
    v_status bb_bb60_stats.status%TYPE;
    v_session_id bb_bb60_stats.session_id%TYPE;
    v_messages bb_bb60_stats.messages%TYPE;
    INSERT_COUNT NUMBER := 1;
    CURSOR curs_aa
    IS
    SELECT * from bb_bb60_stats.activity_accumulator ;
    BEGIN
    OPEN curs_aa;
    LOOP
    FETCH curs_aa into
    v_pk1,
    v_event_type,
    v_user_pk1 ,
    v_course_pk1,
    v_group_pk1,
    v_forum_pk1,
    v_internal_handle,
    v_content_pk1 ,
    v_data,
    v_timestamp ,
    v_status ,
    v_session_id ,
    v_messages;
    INSERT INTO csuh_custom.aa_partitioned
    VALUES
    v_pk1,
    v_event_type,
    v_user_pk1 ,
    v_course_pk1,
    v_group_pk1,
    v_forum_pk1,
    v_internal_handle,
    v_content_pk1,
    v_data,
    v_timestamp,
    v_status,
    v_session_id,
    v_messages
    -- commit after every 100 inserts to avoid large rollback segments
    IF INSERT_COUNT = 25000 THEN
    COMMIT;
    INSERT_COUNT := 1;
    ELSE
    INSERT_COUNT := INSERT_COUNT + 1;
    END IF;
    END LOOP;
    CLOSE curs_aa;

    When I add the END;
    I get
    Line # = 66 Column # = 0 Error Text = PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    pipe

  • "End of File" error 4 when trying to use Advanced TDMS Palette to create a circular file buffer

    I'm using the Advanced TDMS palette to create an on-disk circular buffer. I was able to successfully implement the buffer for a single channel of data.
    However, when I try to write multiple channels of data, I continuously get "End of File Encountered" error 4. I am pre-allocating 60,000 data points for each channel using the "TDMS Set Channel Information" function.
    I am able to (1) Set Next Write Position and (2) perform an Asynchronous Write to the first channel. But when I try to Set Next Write Position to the second channel, I immediately get an error 4.
    The examples have not been helpful as none of them write to different channels in sequence.
    Attached is an example project of what I'm trying to do, coded in 2013SP1.
    Sorry about the file hierarchy, the project is located in the ZIP file here:
    Workspaces\V12000\_V12000 Common Labview Code\Named WF Array\Named WF Array.lvproj
    http://linkd.in/mikele
    Attachments:
    Named WF Array Project.zip ‏1500 KB

    I looked into your project and found that the error comes from Set Next Write Position because the "offset" passed in is out of range. In fact, for continueous logging, you don't need to put the Set Next Write Position in front of the write. Remove this function and you will find your VI can run successfully without throwing out any errors.

  • End of File reached error message when running report

    I am running this report in two different places.  On my own machine it seems to run fine however when I run it for a client on their server I get a message saying end of file reached and the report won't come up.  Any suggestions?

    Hi Jeff,
    In what context are you running the report?  Are you talking about refreshing the data?
    Is this in crystalreports.com or the CR designer or some custom built application? 
    This forum is specifically for the crystalreports.com, Information OnDemand, and Applications OnDemand web applications so this might be the wrong place for your question.  You might want to try the Crystal Reports Design or one of the Crystal Reports SDK forums instead.
    Cheers,
    Steve

  • How to determine the correct moment when Word has finished to write to a docx file

    Hello,
    we are currently passing a document to Microsoft Word for editing and want to take back the changed/saved document when editing is finished. But it seems we have issues to determine the correct moment when Word has for sure saved all changes and
    it is save to take back the file.
    To pass the document to Word we use ShellExecuteEx with the file name. Then we use the Running Objects Table and a File Moniker to wait for the file to be closed.
    Sample code:
    HRESULT hRes = S_OK; 
    CComPtr<IMoniker> spIMoniker; 
    CComPtr<IRunningObjectTable> pRT; 
    hRes = GetRunningObjectTable(0, &pRT); 
    if (FAILED(hRes))
       TWTHROW1(TWERR_ANY_ERROR, hRes, _T("GetRunningObjectTable failed."));
    hRes = ::CreateFileMoniker(m_strTempFilename.AllocSysString(), &spIMoniker);
    if (FAILED(hRes))
       TWTHROW1(TWERR_ANY_ERROR, hRes, _T("CreateFileMoniker failed."));
    while (S_OK == pRT->IsRunning(spIMoniker) && !m_bShutdown)
       Sleep(500);
       continue;
    So we wait for the file to be removed from the Running Objects Table and additionally wait until we can get exclusive access to the file before we take over the changed file. But still it seems to happen that we take the file too early. Hence it
    seems the file is removed from the Running Objects Table by Microsoft Word before saving the file has completed.
    Is this behaviour of Microsoft Word by design? What is the best practice to identify the moment in time when writing the file has completed. Some other applications like Winzip seem to do the same thing.
    Thanks,
    Wolfgang

    Hi WolfGang,
    Thanks for posting in MSDN forum.
    Based on the description, you are developing application with Windows API. I would like to move it to
    General Windows Desktop Development Issues forum.
    The reason why we recommend posting appropriately is you will get the mostqualified pool of respondents, and other partners who read the forums regularly can either share their knowledge
    or learn from your interaction with us.
    Thanks for your understanding.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • When trying to open in external editor I get this warning when going to Photoshop CS6: Could not complete your request because an unexpected end-of-file was encountered.

    Aperture: When trying to open in external editor I get this warning when going to Photoshop CS6: Could not complete your request because an unexpected end-of-file was encountered. I can export and open via Photoshop or open directly from file-just not through external editor. Gerry

    Hi gerry,
    does this happen for a particular image only, or for all images?
    And does this happen only from your account or also from other user accounts?
    Léonie

  • End-of-file on communication channel error when starting database

    Hi All,
    I have small problem, when we specify at startup without any pfile, it will go to read spfile,in our case it gives error end-of-file on communication channel.
    Can anyone please help me to resolve this issue?
    Thank you
    Chirag

    Oracle unable to spawn job slave processes should not prevent the instance from starting - these are not critical system processes and the instance can function without them (as it can when the job queue is set to zero processes).
    The o/s failure message also does not make much sense.. overlapped I/O is Microsoft Windows term for async I/O. This can be used at file I/O level, but is also supported for any other file handle like sockets - thus applicable at the network layer too.
    I'm a bit confused to how a PFILE versus a SPFILE startup can cause this. If that is the case, then surely there are something different ito init instance settings that triggers this error?
    Can you copy and paste the actual SQL*Plus session (as already requested). Show us startup command (and params) used in SQL*Plus and the resulting messages (and errors displayed) in response to the startup.

  • What to do when Photoshop says could not import clipboard because an unexpected end-of-file was encountered

    I have PC, with adobe Photoshop CC 2014 and windows 8. Every time I open Photoshop it says: could not import the clipboard because an unexpected end-of-file was encountered. If I exit the message I still cannot create files or open anything... any suggestions?

    When you load Action and when you create new actions they are saved into you Photoshop Preferences into Actions Palette.psp.  This File is read when you start Photoshop.
    Apple and Microsoft both like to hide important files on users.  Windows search and Apple finder will not find and show hidden files unless you change Mac and Windows setting.  I you getting the error when you start Photoshop there is a shortcut to reset preferences. Hold down Alt, Ctrl, and Shift keys (Mac: Command, Option, Shift) while starting up Photoshop you should be prompted to for an OK to delete preferences.
    If this keeps happening perhaps you have a bad spot on your disk.  Loaded actions are saved into that file so they should show up in the Actions Palette when Photoshop Start Up and read that file during start up. Photoshop Writes that file when you load action sets, when you record and edit actions and most likly also when you close down Photoshop.

  • CS5: "Unexpected end-of-file encountered" when opening a file [was:HELP!]

    I'm trying to open an art file I've been working on for the past week in Photoshop CS5 Extended, and I'm getting a message that my request cannot be complete because an unexpected end-of-file was encountered.  I have no idea what to do.  I've been a Photoshop user for 14 years, and have never seen a message like this before. 

    Hi Curt...I'm new here, so I'll get the hang of it.  Thank you for your quick response.  I'm using the Mac OS X version 10.6.8  I'm a digital artist and was working on a psd file.  I use a wacom tablet and all of a sudden everything stopped responding.  I had to force quit Photoshop and open again.  That's when the window telling me an unexpected end-of-file was encountered.  So much work has gone into this piece of artwork, so needless to say, I'm beyond frustrated.  I had saved this work along the way just so I wouldn't lose it, but now this unexpected twist.  I will try what you suggested to see if it will help. 
    Again THANK YOU!
    Katy

  • Good morning, my photoshop stopped working, it gives error when started, what can it be?  This is the message that appears: Unable to start the program it took a unexpected end of file  I hope answer

    Good morning, my photoshop stopped working, it gives error when started, what can it be?
    This is the message that appears:
    Unable to start the program it took a unexpected end of file
    I hope answer

    Could not initialize Photoshop because an unexpected end-of-file was encountered. | Mylenium's Error Code Database
    Mylenium

  • "Premature end of file" when reading in a GZIP file!

    Hello i'm trying to figure out what may be causing a "Premature end of file" when reading in a GZIP file!
    Basically, what i'm trying to do is read a GZIP file, create an XML file in GZIP format and then validate the GZIPed XML file using the SAX validator and this process works fine for LOW volume data, but for HIGH volume data it seems to have several problems. One problem i was getting was 'Corrupt GZIP trailer', which seems to be a known bug, used an override here and it's ok, and now i'm getting the 'Premature end of file error'.
    Here is the error report, see <<<<<<<<<!
    START: Wed Aug 03 12:03:41 EDT 2005
    Runparms :
    host: ....
    port: ....
    sid: ....
    usr: ....
    site: ....
    val_type: HVPEZ -- previously HVPEX, reason, reading zip file (.gz)
    dbo: NULL
    ddl: /home/......../HLPVAL/DAT/hlp_ddl_file
    table: ......
    db_name: NULL
    dat_file: /..../...../....../xxxxxxx1.dat.gz
    xsd: /home/....../....../XSD/xxxxxxx1.xsd
    sql: NULL
    debug: NULL
    sql query null
    pid: 11751
    xml: /home/.........../...../XML/xxxxxx1.dat_HVPEZ_xml.gz
    rep: /home/.........../...../XML/xxxxxx1.dat_HVPEZ.valrep
    fatalError:
    setValidity:
    Error number : 1
    Error starts on line number : 1302706816
    Error starts on column position: 8
    Error text is : org.xml.sax.SAXParseException: Premature end of file. <<<<<<<<<<<
    org.xml.sax.SAXParseException: Premature end of file.
    Here i'm reading in a GZIPed file, i then generate the XML and write out another GZIPed file, see <<<<<<<<<<:
           try {
            GZIPOutputStream     gz = new GZIPOutputStream(new FileOutputStream(xp.xml_file));  >>>>>>>> out GZIPed
            PrintWriter        outf = new PrintWriter (gz);
            GZIPInputStream      in = new GZIPInputStream(new FileInputStream(xp.dat_file),4096); <<<<<< in GZIPed
            byte[] buf = new byte[4096];int len=0; String[] sa = new String[NUM_COLS]; int bj=0; char[] ca=new char[1500];
            while ((len = in.read(buf)) > 0)
                String hrec = new String();
                for (int b=0;b<len;b++)
                     Byte byt=new Byte(buf); int bi=byt.intValue(); char c=(char)bi; ca[bj]=c;
    if (c == '\n')
    hrec=new String(ca); hrec=hrec.trim();
    for (int k=0;k<1500;k++) ca [k]=' ';
    int prevj=0; j=0;int fcnt=0;
    for (int w=0; w<hrec.length(); w++)
    if (hrec.charAt(w)=='|')
    sa[j]=hrec.substring(prevj,w);fcnt++;
    j++; prevj=w+1;
    sa[j]=hrec.substring(prevj,hrec.length());fcnt++; bj=-1;
    for (int i = 0; i < NUM_COLS; i++)
    if (i>(sa.length-1)) { sToken = new String(); } else { sToken = sa[i]; }
    if (sToken.indexOf('<')>-1 || sToken.indexOf('>')>-1 || sToken.indexOf('"')>-1 ||
    sToken.indexOf('&')>-1 )
    String sToken2 = new String();
    sToken2 = normalize(sToken);
    sToken = sToken2;
    outf.write(" <"+_columnNames[i]+">"+sToken+"</"+_columnNames[i]+">"+"\n");
    outf.write(" </"+FILE_NAME+">"+"\n");
    bj++;
    outf.write("</hlp_data>"+"\n");
    outf.flush(); <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< here if tried every combination of close command ect.
    outf.close();
    gz.finish();
    gz.close();
    in.close();
    Here i'm reading the GZIPed file from the previous program and this is where the 'Premature end of file' error is occurring. Notice that i'm using an extended class Called WorkingGZIPInputStream, this is to bypass the error message 'Corrupt GZIP trailer' message that seems to occur when processing high volume files, here's a previous link on issue:
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=011624
           HlpValSax1  sx = new HlpValSax1();
           SAXParser   sp = sx.getParser(xp.xsd_file);
           if (
                  xp.val_type.substring(0,5).equals("HVPEZ")
               || xp.val_type.substring(0,5).equals("HVPEX")
               || xp.val_type.substring(0,5).equals("HVOEX")
               WorkingGZIPInputStream is = new WorkingGZIPInputStream(new FileInputStream(xp.xml_file),4096); <<<<<<<<<<
               sp.parse(is,dh);
           else
              File file      = new File(xp.xml_file);
              InputStream is2 = new FileInputStream(file);
              sp.parse(is2,dh);
         catch (FileNotFoundException nf) {System.out.println(nf);}
         catch (SAXException sa)          {System.out.println(sa);}
         catch (IOException  io)          {System.out.println(io);}

    Turns out things were not exactly the same. When I had done it from disk I would always create a new InputStream when reading the resource, when doing it from the Jar I was reusing it.

  • Blank Lines at end of file when using Variable Substitution in File Adapter

    Hi all,
    I'm using variable substitution in a File Adapter, it's refers an element of message, like:
    filename    payload:MESSAGE_INTERFACE,1,FILENAME,1
    The variable substitution is working right, but it's append a BLANK LINE at end of file.
    Anyone knows how to solve this problem ?
    Thanks in advance.

    Hi Regis,
    I suppose you're using content conversion?
    if so try adding
    <b>endSeparator</b> = '0'
    to your last element
    this will delete the default line break at the end
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions">XI FAQ - Frequently Asked Questions</a>

Maybe you are looking for