Write / read objects to/from File

Hello,
I have a problem with the writing and reading objects to/from a file.
So what excatly I'm trying to is:
I have a class Data. A thread creates constantly (until some limit) objects of this class Data.
Once an object is created, is placed in a buffer (I wrote my own class DataBuffer extention of LinkedList).
I have a limit on this buffer, so when the limit is reached, another thread starts getings objects from the buffer, writes them on the disk and removing them from the buffer.
I'm putting the object always on the "top" and I'm reading them and removing always from the "bottom" of the buffer (FIFO).
For writing the objects Data to the file, I'm using a FileOutputStream and ObjectOutputStream:
I have something like that:
FileOutputStream fos = new FileOutputStrea("file_name");
ObjectOutputStream oos = new ObjectOutputStream(fos);after that I have this:
while(size > i ){
                    try {
                         Data d = buff.getData();
                         //write to File
                         oos.writeObject(buff.getData());
                         oos.flush();
                         buff.removeData();
                         System.out.println("written data " + d);
                         i++;
                    } catch (IOException e) {
                         e.printStackTrace();
               }here size is the limit for the buffer.
So, when the size is equal to the total number of objects that were created and placed in the buffer, I have no problems with the writing/reading from the file.
But if size is equal, for example, to the half of the total number of objects that were created, I have a problem.
A more detailed exmple is:
10 objects were created, the 10 objects were places to the buffer, a test was made and all the objects were written on the disk -> writing and reading are OK.
if 10 objects were created, and I want to write 5 objects, and after that more 5, the first thing I remarqued is that the size of the file is different from the size of the file created by the first method. Second thing is when I'm reading from the file I can read only 5 objects and after that I have this exception:
java.io.StreamCorruptedException : invalid type code : AC
So ... is anyone has an idea why I have this problem?
PS. For reading from the file I'm using another thread that executes this code:
fis = new FileInputStream(readFile);
                    ois = new ObjectInputStream(fis);
                    while(true){
                         try{
                              Data d = (Data)ois.readObject();
                              System.out.println("data read " + d); //here I'm displaying the object that was read
                              buff.putData(d);
                         }catch(EOFException e){
                              break;
                    ois.close();
                    fis.close();
               }catch (FileNotFoundException e) {
                    e.printStackTrace();
               }catch(IOException e){
                    e.printStackTrace();
               }catch (ClassNotFoundException e) {
                    e.printStackTrace();
               }Regards,
Anton
PS. At present I'm writing first all the Data objects, and after that I'm trying to read from the file.
Edited by: anton_tonev on Oct 5, 2007 4:14 AM

Hello again :)
Finally I found the solution :)
In fact it is important to not to close the FileOutputStream and ObjectOutputStream until all the data was written on the disk.
What I mean:
in the begining of the program you have to open these two streams and write down the data that comes from somewhere.
But you musn't close these streams before the final writing on the disk.
It must look like this:
1 Open file stream & opent object stream
2 you're writing your all objects: one by one; 10 by 10 or as you wish ... but after each writing down you don't close the streams
3 you already finished with the writing, (the end of your program), now you can close the streams.
Unfortunatly I don't know why if I write the data and close the stream every time, after that it is impossible to append new data (with reopen the file)

Similar Messages

  • How to write an object to a file.

    I have a LinkedList called my data. Is there a way to write this object to a file instead of having to convert the data to delimited string values and storing it in a sequential file?

    this is how i write and read objects to a file:
         public void write() {
              try {
                   oos = new ObjectOutputStream(new FileOutputStream(fileName));
                   oos.writeObject(data);
                   oos.flush();
                   oos.close();
              } catch (Exception e) {
                   System.out.println(e.toString());
         public void read() {
              try {
                   ois = new ObjectInputStream(new FileInputStream(fileName));
                   data = (LinkedList)ois.readObject();
                   ois.close();
              } catch (FileNotFoundException fnf) {
                   System.out.println("noFileFound");
              } catch (Exception e) {
                   System.out.println(e.toString());

  • [Solved] Shell script to read unhashed lines from file.

    Hello.
    I want to write a shell script  (it can be bash,sh,ksh,csh or zsh) that will be:
    1.Read unhashed lines from file named mirrors.conf.
    2.Put them in ~/.profile as PKG_PATH=line catted from mirrors.conf.
    Just like as mirrors.conf file for pacman.
    Now it can cat lines but how to put them in files as PKG_PATH?
    Thanks for answers.
    Last edited by SpeedVin (2010-03-01 17:33:20)

    res wrote:
    ^ IFS is not necessary here; it won't mess with the white space:
    $ echo 'args with formatted spaces ' | while read -r; do echo "$REPLY"; done
    args with formatted spaces
    It matters for leading/trailing whitespace:
    $ echo ' after some ' | while read -r line; do echo "<$line>"; done
    <after some>
    $ echo ' after some ' | while IFS= read -r line; do echo "<$line>"; done
    < after some >

  • Why doesn't "include/object/text from file" work?

    I want to include (link) text from other Word documents to a  main  Word document and I use "include/object/text from file" (Word function)
    It works fine when I do so in "H:", but doing exactly the same in the Sharepoint environement result in "nothing" (nothing happens)
    It DOES work if I link from a document saved in Sharepoint to a "H:" - document, but that is of no use since I need all the documents to be stored in Sharepoint.
    Guess it has to do with the set up och Sharepoint.
    Greatful for any tips!

    Hi,
    Did you mean insert a object in the documents?
    Did you open the file with the local application or office web application?
    In the office web application, it doesn’t have the function to insert a object in the browser.
    I had tested with some word files in the library, open the word files with the local application, then insert file using the insert object function.
    It worked without any issue.
    What’s more, I had tested with Office 2010 and Office 2013, they all worked.
    Did the issue occur in other libraries? You can create a new library to check whether it works.
    You can also download a copy for the issued file, then open it in the local machine to check whether it works in the local machine.
    Thanks & Regards,
    Jason
    Jason Guo
    TechNet Community Support

  • Read image direct from file server

    hello, need to help me somebody.
    A like to create form , what read image direct from file server, without store in database.
    Please help me.

    Hi you may go through the below post to find what could be a better way to do that.
    http://forum.java.sun.com/thread.jspa?threadID=5163829
    REGARDS,
    RaHuL

  • Need help with EXS24 "read velocity range from file name"

    I am trying to import 127 drum samples to a single key using the option shown here. The option says "Map to key dropped on and read velocity range from file name". I can find no documentation in the manuals on how to do this. What is the syntax required in the file name to make this work? I need to do several of these imports. The capability is cleary there, but I need help on how the file name should be formatted. My thanks to anyone who can help.

    Hi
    Not a direct answer to your question, but if you are doing a lot of sample mapping etc, you may want to check out Redmatica's KeyMap Pro or the simpler Keymap 1:
    http://www.redmatica.com
    CCT

  • EXS24 read root key from file name only

    Has anyone encountered this with EXS24 in Logic 7? If you set preferences to "read root key from file name only" then EXS reads the root key from the file itself when loading samples. On the other hand if you set them to "read root key from file only" then it reads the root key from the file name. Or am I just imagining this?
    P.S. if anyone from Apple is reading, could you please update EXS24? It's a bit primitive by today's standards.

    Hi
    Not a direct answer to your question, but if you are doing a lot of sample mapping etc, you may want to check out Redmatica's KeyMap Pro or the simpler Keymap 1:
    http://www.redmatica.com
    CCT

  • How to read some images from file system with webdynpro for abap?

    Hi,experts,
    I want to finish webdynpro for abap program to read some photos from file system. I may make MIMES in the webdynpro component and create photos in the MIMES, but my boss doesn't agree with me using this way. He wish me read these photos from file system.
    How to read some images from file system with webdynpro for abap?
    Thanks a lot!

    Hello Tao,
    The parameter
       icm/HTTP/file_access_<xx>
    may help you to access the pictures without any db-access.
    The following two links may help you to understand the other possibilities as well.
    The threads are covering BSP, but it should be useful for WebDynpro as well.
    /people/mark.finnern/blog/2003/09/23/bsp-programming-handling-of-non-html-documents
    http://help.sap.com/saphelp_sm40/helpdata/de/c4/87153a1a5b4c2de10000000a114084/content.htm
    Best regards
    Christian

  • Error 2 for write/read access to a file. File = /usr/sap/SID/SYS/global/999

    hi
    when i am checking update statistics in  db13  it is not creating any log information, and more over it is creating error in sm21 like
    Error 2 for write/read access to a file. File = /usr/sap/<SID>/SYS/global/999JOBLG/0001X06000603X23459.
    can any one help me.
    regards
    subhani.

    Duplicate post
    Read and Follow the Forum Rules

  • Write/read image to avi file, VI works incorrectl​y from the second run

    Hi everybody, in my labview I write image from IMAQ USB to avi file and read image from avi file, the VI runs correctly at the first run then after that it goes wrong, I can write/read only one frame and it terminates automatically. Does anybody know why and how to solve this?
    Thanks a lot,
    Hannah

    Without seeing your code I can't comment specifically, but if it runs correctly the first time and then stops be looking for something that is not getting reinitialized correctly. Also what exactly do you have to do to get it to work again? Close and reopen the VI? Restart LV? Restart the computer?
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • How to Read specific data from file and do a calculation and display on the output

    FYI: Below is the function use for the writing:
    -OpenFile(use ASCII)
    -sprintf
    -WriteFile
    Example: Output from the doc file
    …EndTime: 09:34:48 program time: 0.567663 sec
    …EndTime: 09:36:48 program time: 0.666666 sec
    My objective is to read data 0.666666 (FYI: is last sentence of the file) to do some calculation. How can we read specific data(specific location) from file..
    Any advice or help?
    What is the function needed?

    I would consider counting line feeds and checking for end-of file to isolate the last line, which then can be read using fscanf...
    Have a look at getc...
    character = fgetc ( stream );
    if ( character == '\n' ) // new line
    if ( character == EOF ) // end-of-file

  • Read object list from a transport datafile

    Hallo,
    does anyone know a way to read the object list from a transport datafile.
    The problem is, that the rewuest is not added to the STMS an so the files are not known by the STMS. But data and cofile is stored in the corresponding folders of the transport management system.
    Thanks
    Arnfried

    Hello,
    Have you tried to add the request to the import queue?
    While displaying the import  queue  Extras->Other Requests->Add
    Regards
    Greg Kern

  • How to read a string from file & assign the val to a variable in batch file

    Hi,
    How to read a string from a file and assign the value to a variable then return the value to the screen in windows batch file?
    Any suggestions?
    thanks.

    Unless this is a homework question then I don't see the purpose of doing this, but....
    You should be looking a the supplied package utl_file to get the string out of the file, dbms_output to display the string and then google windows batch/command files calling sqlplus to execute your program.
    Andre

  • Write/read struct in binary file

    Hi to all,
    I created a struct profile defined as follows:
    typedef struct profile {
    char name [30];
    float power;
    double frequency;
    struct profile * next;
    I can write the structures in a file, but I should do so that when you try to insert a struct, you control the field name and only if there is no other struct with that name,it is inserted in the file .
    Please help me !!!
    Solved!
    Go to Solution.

    I tried this way
    #include <ansi_c.h>
    #include <cvirte.h>
    char nuovo[50];
    int cmp;
    FILE *fp;
    struct profilo
    char nome[50];
    float potenza;
    double frequenza;
    }p;
    int main (int argc, char *argv[])
    if (InitCVIRTE (0, argv, 0) == 0)
    return -1; /* out of memory */
    fp = fopen ("c:\\Program Files (x86)\\National Instruments\\CVI81\\ESERCITAZIONI\\scrittura file 2\\profili.txt", "ab+");
     printf("Insert name: \n");
    scanf("%s",nuovo);
    do
    fseek(fp,sizeof(struct profilo),SEEK_SET);
    fread(&p,sizeof(struct profilo),1,fp);
    //printf("nome: %s\n",nuovo);
    //printf("p.nome: %s\n",p.nome);
    p.nome==nuovo;
    printf("p.nome dopo: %s\n",p.nome);
    cmp=strcmp(p.nome,nuovo);
    if(cmp=0)
      printf("Already exists\n");
    fclose(fp);
    else
    p.nome==nuovo;
    scanf("%f%lf",&p.potenza,&p.frequenza);
    }while(!feof(fp));
    fclose(fp);
    return 0;
    but don't work . 

  • Problem with reading special char from file

    Hello Oracle community,
    Got a problem when reading from a file. I am using a croatian keyboard and trying to read special charachters (ČĆŽŠĐ) from a file.
    declare
      l_file utl_file.file_type;
      s varchar2(200);
    begin
      l_file := utl_file.fopen('test_dir', 'test.txt', 'R');
      loop
        utl_file.get_line(l_file, s);
        dbms_output.put_line(s);
      end loop;
    exception
      when no_data_found then
        utl_file.fclose(l_file);
    end;But I keep getting this in dbms_output: ČƎŠĐ. For some reason it keeps skipping 2 chars Š and Ž. If I try to insert or update data the values are show correctly. What could be the cause of such a problem?
    Best regards,
    Igor

    Hi Igor,
    Looks like a NLS_LANGUAGE issue. Check the following threads:
    UTL_FILE and NLS_LANG setting
    Re: Arabic characters not displaying in Forms
    Regards,
    Sujoy

Maybe you are looking for