Reading an object from a binary file

i am writing objects into my binary file using printwriter class. i am able to write objects into the file but i am having problems reading the object from the file. is there any other way of going about it. i tried using the objectoutputstream and object input stream class. but i am getting run time errors coz of something to do with serialization
i am storing records as a object into a binary file so that it is easy to seek my records

Of course you have trouble reading objects after you wrote them with a PrintWriter.
You should rather have fixed the Serialization errors: only objkects that implement Serializable correctly can be serialized.

Similar Messages

  • Reading objects from a binary file works but crashes LabVIEW on exit

    I've been hunting for the source of some crashes on LabVIEW exit and I was finally able to track it down to this. In my application I wrap measurements into objects that I stream into a binary file during the inspection. In another application I read the file again to browse and analyze the measurements. All this seems to work just fine except that the reading part causes LabVIEW to crash once I close the IDE. Built applications don't report any crashes but I am afraid if it might still cause some instability or unexpected behaviour.
    The snippet below represents the writing and reading scheme I use and with which I am able to reproduce the problem every time. I attached the project for testing it.
    Parts from the internal warning report:
    #OSName: Windows 8.1 Pro N
    #AppName: LabVIEW
    #Version: 13.0f2 32-bit
    DWarn 0xEFBFD9AB: Disposing OMUDClass definition [LinkIdentity "Class 1.lvclass" [ My Computer] even though 1014 inflated data instances still reference it. This will almost certainly cause a crash next time we operate on one of them.
    Possible path leak, unable to purge elements of base #0
     The full log is also attached.
    Notes:
    Remember: the reading works without any problems, the crash after LabVIEW exit is what I'm concerned about
    Seems to only happen with classes/objects—not the default LabVIEW Object, though
    Prepending array size or different byte orders make no difference
    The writing is time critical, the reading is not, in case you wish to suggest other options
    Has anyone else run into this? Should I be concerned for the built applications or can this be simply ruled as an IDE problem?
    Solved!
    Go to Solution.
    Attachments:
    test_project.zip ‏16 KB
    lvlog.txt ‏5 KB

    Right off, if you say you can read and write lv objects, try casting your object as a lv object before saving it. The lv object is the ultimate parent of all classes.
    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

  • To read structure variable from a binary file

    Hi Everyone,
    Iam having a binary file created by c++.It contains structure  like this one...
    struct
          char name[2];
          unsigned short num;
          char identity[4];
          double date;
          union
              byte id[4];
              int sizeconst;
              int size;
    I want to read this struct file in labview. How can i do that?

    Once I had the same problem, I've asked NI-support and they said to me because of different kind of reading method that that operation is impossibile to do, so the solution to solve the problem has been to create a C++ library that reads the structure from the file and makes disponible the data. After, I've called the library by "Call by library function" in my Labview software.
    Ricky
    Italian Developer engineer
    www.www.selt-sistemi.com

  • How to create an object of a binary file?

    Does anyone know how I may create a serializable object of a binary file?
    Thanks.

    Sorry for the late reply.
    No, I'm not trying to deserialise a serialised object. My intent is to create a serialisable object from a binary file and then store this object in a JMS Queue.
    One option is to create a byte array of the binary file. Wondering if there are other options available.

  • Reading an Array of Objects from a .bin file!

    Hey, at the moment I'm creating a program whereby I write a set of objects onto a bin file, in this case an array of objects with a String name/county, and int population/area.... I'm not trying to read it back from the bin file and encountering trouble! I've managed to get it working using plain objects, however I want to be able to read in arrays of objects. The file itself compiles, however during running I get this error
    java.lang.NullPointerException
    at RecordFiles.CoastalRead.main(CoastalRead.java:33)
    at RecordFiles.__SHELL16.run(__SHELL16.java:6)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at bluej.runtime.ExecServer$3.run(ExecServer.java:774)
    Here is the program itself,
    import java.io.*;
    public class CoastalRead {
        public static void main(String[] args) {
            CoastalTowns towns[] = new CoastalTowns[50];
              towns[0] = new CoastalTowns();
              towns[1] = new CoastalTowns();
              towns[2] = new CoastalTowns();
              towns[3] = new CoastalTowns();
              towns[4] = new CoastalTowns();
              String name, county;
              int population, area;
            try {
                FileInputStream fileIn =
                        new FileInputStream("CoastalTownsBin.bin");
                ObjectInputStream in = new ObjectInputStream(fileIn);
                for (int i = 0; i < towns.length; i++){
                 towns[i] =(CoastalTowns) in.readObject();
                   System.out.println("Deserialized File...");
                       System.out.println("Name: " + towns.name);
              System.out.println("County: " + towns[i].county);
         System.out.println("Population: " + towns[i].population);
              System.out.println("Area: " + towns[i].area);
    in.close();
    fileIn.close();
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}
    +I'd appreciate a fast reply!+ And if someone needs the writing class I've used, I can post it asap.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    CoastalTowns towns[] = new CoastalTowns[50];
    towns[0] = new CoastalTowns();
    towns[1] = new CoastalTowns();
    towns[2] = new CoastalTowns();
    towns[3] = new CoastalTowns();
    towns[4] = new CoastalTowns();Why create an array with a size of 50 and then only fill 5 elements?
    Why bother filling any elements at all when you are reading the objects from a file?
    What happens if there are less than 50 objects in your file?
    I will assume CoastalTowns holds info about a single town, so why is it pluralised? Do you have a class called Dog or Dogs, Chair or Chairs, Person or People?
    } catch (IOException i) {}
    catch (ClassNotFoundException c) {}DO NOT swallow exceptions. At the very least put in a call to printStackTrace so you know if/when an exception occurs.
    I'd appreciate a fast reply!I typed as fast as I could but unfortunately I'm still and hunt and peck guy.

  • How to read appended objects from file with ObjectInputStream?

    Hi to everyone. I'm new to Java so my question may look really stupid to most of you but I couldn't fined a solution by myself... I wanted to make an application, something like address book that is storing information about different people. So I decided to make a class that will hold the information for each person (for example: nickname, name, e-mail, web address and so on), then using the ObjectOutputStream the information will be save to a file. If I want to add a new record for a new person I'll simply append it to the already existing file. So far so good but soon I discovered that I can not read the appended objects using ObjectInputStream.
    What I mean is that if I create new file and then in one session save several objects to it using ObjectOutputStream they all will be read with no problem by ObjectInputStream. But after that if in a new session I append new objects they won't be read. The ObjectInputStream will read the objects from the first session after that IOException will be generated and the reading will stop just before the appended objects from the second session.
    The following is just a simple test it's not actual code from the program I was talking about. Instead of objects containing different kind of information I'm using only strings here. To use the program use as arguments in the console "w" to create new file followed by the file name and the strings you want save to the file (as objects). Example: "+w TestFile.obj Thats Just A Test+". Then to read it use "r" (for reading), followed by the file name. Example "+r TestFile.obj+". As a result you'll see that all the strings that are saved in the file can be successfully read back. Then do the same: "+w TestFile.obj Thats Second Test+" and then read again "+r TestFile.obj+". What will happen is that the strings only from the first sessions will be read and the ones from the second session will not.
    I am sorry for making this that long but I couldn't explain it more simple. If someone can give me a solution I'll be happy to hear it! ^.^ I'll also be glad if someone propose different approach of the problem! Here is the code:
    import java.io.*;
    class Fio
         public static void main(String[] args)
              try
                   if (args[0].equals("w"))
                        FileOutputStream fos = new FileOutputStream(args[1], true);
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        for (int i = 2; i < args.length ; i++)
                             oos.writeObject(args);
                        fos.close();
                   else if (args[0].equals("r"))
                        FileInputStream fis = new FileInputStream(args[1]);
                        ObjectInputStream ois = new ObjectInputStream(fis);
                        for (int i = 0; i < fis.available(); i++)
                             System.out.println((String)ois.readObject());
                        fis.close();
                   else
                        System.out.println("Wrong args!");
              catch (IndexOutOfBoundsException exc)
                   System.out.println("You must use \"w\" or \"r\" followed by the file name as args!");
              catch (IOException exc)
                   System.out.println("I/O exception appeard!");
              catch (ClassNotFoundException exc)
                   System.out.println("Can not find the needed class");

    How to read appended objects from file with ObjectInputStream? The short answer is you can't.
    The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
    Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
    Not trivial, but that's how you'd do it.

  • I can't read a Object from file, Please help me

    i want to write a Object into File. this is code of Object
    class objStoreCus implements Comparable, Serializable
    String customerID = new String();
    String customerName = new String();
    String customerEmail = new String();
    objStoreCus(String cusID, String cusName, String cusEmail)
    customerID = cusID;
    customerName = cusName;
    customerEmail = cusEmail;
    objStoreCus(){}
    public int compareTo(Object o)
    objStoreCus oS = new objStoreCus();
    oS = (objStoreCus)o;
    return(customerEmail.compareTo(oS.customerEmail));
    private void writeObject(ObjectOutputStream s) throws IOException {
    s.defaultWriteObject();
    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
    try
    s.defaultReadObject();
    }catch(IOException ie){throw new IOException();}
    catch(ClassNotFoundException cnt){throw new ClassNotFoundException();}
    And I was wrote above Object into File by this code :+
    FileOutputStream fos;
    ObjectOutputStream oos;
    FileInputStream fis;
    ObjectInputStream ois;
    public void writeObjToFile(objStoreCus obj)
    try
    fos = new FileOutputStream("Exrcise3.ex3", true);
    }catch(FileNotFoundException fnfe){}
    try
    oos = new ObjectOutputStream(fos);
    //ghi doi tuong vao file
    oos.writeObject(obj);
    //dong stream
    oos.close();
    fos.close();
    }catch(IOException ie){}
    But i can't read above Object from file. allway have a Exception occur "StreamCorruptedException".
    this is code read Object form file :
    *parameter is ArrayList will be store Object from file.
    public void readObjFromFile(ArrayList al)
    try
    fis = new FileInputStream("Exrcise3.ex3");
    }catch(FileNotFoundException fnfe){}
    try
    ois = new ObjectInputStream(fis);
    while(true)
    try
    objStoreCus osc = new objStoreCus();
    osc = (objStoreCus)ois.readObject();
    System.out.println(osc.customerEmail);
    }catch(Exception e)
    e.printStackTrace();
    //System.out.println();
    break;
    ois.close();
    fis.close();
    }catch(IOException ie){}
    }

    Problem lies in
    os = new FileOutputStream("Exrcise3.ex3", true);
    You are trying to append to that file, You should always use new file to serialize objects.
    os = new FileOutputStream("Exrcise3.ex3");
    Try with above line.

  • How to read OLE objects from Access ??

    Hi,
    I have an field of type OLE in my Access Database table. This field has some files stored in it in the form of attachment. The file types of the OLE objects can be different (xls,txt,doc). Now, I want to query the database and find the extension of the files and save it occordingly using java.
    I'm using the following now.
    JdbcOdbcInputStream jois = (JdbcOdbcInputStream) rs     .getBinaryStream("SupportingData");
    byte[] supportingData = jois.readData();
    String data = new String(supportingData);
    I'm getting data in binary format and when I try to look into it, all I can see is the header info of the file.
    Is there anyother way to read the OLE object easily ?
    Please suggest.
    Thanks,
    Mary

    How to read appended objects from file with ObjectInputStream? The short answer is you can't.
    The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
    Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
    Not trivial, but that's how you'd do it.

  • How to read some lines from a text file using java.

    hi,
    i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
    we only want to read the file upto the first Occurrence of "TEXT" string.
    How to do it ,,,
    Kinldy give the code
    Regards,
    Sagar
    this is the text file
    dfgjdjj
    sfjhjkd
    ghjkdg
    hjkdgh TEXT
    ikeyt
    ujt
    jk
    tyk TEXT
    rukl
    r

    Hendawy wrote:
    Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
    Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
    The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
    Edited by: sabre150 on Apr 29, 2009 2:13 PM

  • I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?

    I have a VI and an attched .txt data file. Now I want to read the data from the .txt file and display it as an array in the front panel. But the result is not right. Any help?
    Attachments:
    try2.txt ‏2 KB
    read_array.vi ‏21 KB

    The problem is in the delimiters in your text file. By default, Read From Spreadsheet File.vi expects a tab delimited file. You can specify a delimiter (like a space), but Read From Spreadsheet File.vi has a problem with repeated delimiters: if you specify a single space as a delimiter and Read From Spreadsheet File.vi finds two spaces back-to-back, it stops reading that line. Your file (as I got it from your earlier post) is delimited by 4 spaces.
    Here are some of your choices to fix your problem.
    1. Change the source file to a tab delimited file. Your VI will then run as is.
    2. Change the source file to be delimited by a single space (rather than 4), then wire a string constant containing one space to the delimiter input of Read From Spreadsheet File.vi.
    3. Wire a string constant containing 4 spaces to the delimiter input of Read From Spreadsheet File.vi. Then your text file will run as is.
    Depending on where your text file comes from (see more comments below), I'd vote for choice 1: a tab delimited text file. It's the most common text output of spreadsheet programs.
    Comments for choices 1 and 2: Where does the text file come from? Is it automatically generated or manually generated? Will it be generated multiple times or just once? If it's manually generated or generated just once, you can use any text editor to change 4 spaces to a tab or to a single space. Note: if you want to change it to a tab delimited file, you can't enter a tab directly into a box in the search & replace dialog of many programs like notepad, but you can do a cut and paste. Before you start your search and replace (just in the text window of the editor), press tab. A tab character will be entered. Press Shift-LeftArrow (not Backspace) to highlight the tab character. Press Ctrl-X to cut the tab character. Start your search and replace (Ctrl-H in notepad in Windows 2000). Click into the Find What box. Enter four spaces. Click into the Replace With box. Press Ctrl-V to paste the tab character. And another thing: older versions of notepad don't have search and replace. Use any editor or word processor that does.

  • Reading one line from a text file into an array

    i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
    public static void readAndProcessData(FileInputStream stream){
         InputStreamReader iStrReader = new InputStreamReader (stream);
         BufferedReader reader = new BufferedReader (iStrReader);
         String line = "";          
         try{
         int i = 0;
              while (line != null){                 
                   names[i] = reader.readLine();
                   score[i] = reader.readLine();
                   line = reader.readLine();
                   i++;                
              }catch (IOException e){
              System.out.println("Error in file access");
    this section calls it:
    try{                         
         FileInputStream stream = new FileInputStream("ISU.txt");
              HighScore.readAndProcessData(stream);
              stream.close();
              names = HighScore.getNames();
              scores = HighScore.getScores();
         }catch(IOException e){
              System.out.println("Error in accessing file." + e.toString());
    it gives me an array index out of bounds error

    oh wait I see it when I looked at the original quote.
    They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens.

  • Reading Each String From a text File

    Hello everyone...,
    I've a doubt in File...cos am not aware of File.....Could anyone
    plz tell me how do i read each String from a text file and store those Strings in each File...For example if a file contains "Java Tchnology forums, File handling in Java"...
    The output should be like this... Each file should contains each String....i.e..., Java-File1,Technology-File2...and so on....Plz anyone help me

    The Java� Tutorials > Essential Classes: Basic I/O

  • Populate a table reading the data from a TXT file

    how can I populate a table reading the data from a TXT file?
    thanks

    Hey Kevin!
    Using FORMS.TEXT_IO to bulk load data from a file strikes me as re-inventing the wheel. It is just about justifiable in a self-service environment, but I regard the EXTERNAL TABLE is a better solution for that situation as well.
    The same applies to UTL_FILE. I think the ability to read text with UTL_FILE is primarily intended for read file-based configuration or file manipulation/processing rather than data loading.
    Re-writing a text file into SQL statements is too much like hard work (even with an editor that supports macro definition and regular expressions) for no real benefit. You lose all the bulk load peformance you would get from SQL*Loader. But for QAD I'd probably let you off with it.
    You missed out one obvious alternative: using Java to turn the contents of an XML file into a CLOB and inserting it into a table which is read by a PL/SQL procedure that parses the XML records and insert the retrieved data into a table.
    Stay lucky, APC

  • How to read every line from a text file???

    How can i read every line from my text file ("eka.txt")
    now it only reads the first line and prints it out.
    What is wrong with this?
    import java.io.*;
    import java.util.*;
    class Testi{
         public static void main(String []args)throws IOException {
         BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
    File inputFile = new File ("eka.txt");
    FileReader fis =new FileReader(inputFile);
    BufferedReader bis = new BufferedReader(fis);
    String test=bis.readLine();
    String tmp= "";
    while((bis.readLine().trim() != null)) {
    int spacefound=0;
    int l=test.indexOf(" ");
         for(int i=0;i<test.length();i++){
         char c=test.charAt(i);
         if(c!=' ') tmp+=""+c;
         if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
         tmp+=""+c;
         spacefound++;
         if(tmp.length()==l) {
         System.out.println(tmp);
         tmp="";
         spacefound=0;
         if(tmp.length()<l){
         for(int i=0;i<=(l-tmp.length());i++)
         tmp+=""+' ';
         System.out.println(tmp);

    Try this code, Hope it servers your purpose.
    import java.io.*;
    import java.util.*;
    class Testi {
         public static void main(String []args)throws IOException {
              BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
              File inputFile = new File ("Eka.txt");
              FileReader fis =new FileReader(inputFile);
              BufferedReader bis = new BufferedReader(fis);
              String test=bis.readLine();
              while(test != null) {
                   StringTokenizer st = new StringTokenizer(test," ");
                   while(st.hasMoreTokens())
                        System.out.println(st.nextToken());
                   test = bis.readLine();
    }Sudha

  • How do i read complete line from a text file in j2me?????

    how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..

    That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..

Maybe you are looking for

  • How to delete or activate the deletion flag for the sales order line item

    Hi All, I  have one Cust order & with referance to that cust order one production order is created . The production order user has done the Goods issue with 261 movement type  & GR wi 101 before 4 months back , & he has reverse  the GR  with 102 on t

  • Calling setString() method in JDBC

    Hello, I have a java class which I used for database activities. I have a method called setStrValues(int position, String strValue)  { callablestmt.setString(position, strValue); }Now I need to generalize this method so that I can use setStrValues me

  • Acrobat SDK and MFC

    Hi, sorry for this noob questions, I have just graduated, and have no experience with MFC or the Acrobat sdk. I have tried for some while to get a dialogbox opened and have followed the plugin apps developer guide and this guide http://www.adobeforum

  • Issue resolving a classloader error

    Good Day. I've created and deployed ear that references another application (ear). For example, I have an application named: sampleapp.ear. That file deployed sucessfully. When I try to use that application http://localhost:50000/sampleapp/start.jsp?

  • We are unable to load all your plans & products. Please try again.

    I'm trying to change the billing information for my account but no matter which browser I log in with, I get the following message in my OVERVIEW tab, under Plans & Products: We are unable to load all your plans & products. Please try again. Even if