Writing InputStream object to a file.

I want to write a InputStream object to a file. How can this be done?
Help please

Fucking spammer.
http://forum.java.sun.com/thread.jspa?threadID=612286&messageID=3377965#3377965

Similar Messages

  • Writing XML Object to a File

    Hi, I am using InDesign JavaScript to make an XML object in memory. When my script is done, I want to write the XML to a file. When I run the code below, the file is created, but the XML is not written to the file. Any help would be appreciated. Thanks. Rick
    #target indesign
    var partsMap = <partsMap />;
    savePartsMap (partsMap);
    function savePartsMap (partsMap) {
        var partsFile;
        // Make a File object for the parts map XML file.
        partsFile = new File("E:\\Test.xml");
        // Open the map file.
        partsFile.open("w");
        partsFile.write(partsMap);
        partsFile.close();

    Add partsFile.encoding = 'UTF-8'; right after your File instantiation.
    I'm not sure but you also might want to write partsMap.toXMLString() instead of the partsMap.toString() you're implicitly writing.
    Jeff

  • Emergency! Writing an object into a file (NotSerializableException)

    Hi, I am now working in a project. I came across a serialization problem which I am spending so many days and haven't gotten any solution.
    I assume that the problem is caused by the complexity of class design in a package. The saved object extends all of 9~11 classes in which some are abstract class, some are listening interface class, some are just normal class but extending from GUI components such as JTree, JFrame and so on. Besides static is spred over anywhere in the classes.
    code:(No problem here)
    output = new ObjectOutputStream( new eFileOutputStream( fileName ) );
    output.writeObject(prj);
    output.flush();
    Futher, the 'prj' object is proved to be very serializable as a result of "isSerializable()" function before writting in to a file. However it invokes IOExceptions, isn't it funny?
    ex:
    A--B--C--D--E
    |
    |
    F G H
    | |
    I J
    |
    prj
    In the example of above, is it possible to store all the state of objects A to J by storing prj so that I can re-construct the whole of objects relations and the members in them from the stored 'prj'?
    Back to the original problem, then...
    Do I have to get rid of all the static declarations of parent classes?
    Do I have to serialize each single classes one by one without being greedy tryint to store all of the state of objects linked to 'prj' at once?
    Do I have to get every single objects implemented 'Serializable' including abstruct and interface classes if they contains static declaration or someting unserializable?
    Please give me any help or hint, anything I am appreciate for.

    The problem is not very clear. Some code snippets might help. Especially the Exception details.Your object graph is somewhat confusing too.
    To answer your questions, the default Serialization (where the object prj, though extends java.io.Serializable, DOESN'T implement writeObject() and readObject() methods) will succeed only if all the reachable super classes in the graph are a. either implement Serializable or b. have no-argument constructors. In case of b., it's the responsibility of the object prj to re-establish the state of the parent classes from the serialized stream. You can do that by implementing writeObject() and readObject() methods themselves.
    The transient and static fields are never serialized. So if you want to preserve the value of a static field then you'll have to either a. explicitly serialize that field out to the ObjectOutputStream and read it back from the ObjectInputStream in the writeObject() and readObject() methods or b. using reflection where you can get the Class name and get the static field value from the corresponding 'Class' data type also using reflection (object.getClass().getField("fieldName").getValue(null)).

  • Need help (desperately) '^_^ in writing multiple objects in a single file

    For all those Java guru out there please help me,
    I want to write a simple application that can serialize objects in a single file. Currently I know how to serialize one object in one file using the ObjectOutputStream's writeObject () method.But the problem is that if i have 10.000 objects to serialize then I will have 10.000 file in my HD. To simplify things I want to write those 10.000 objects in a single file. But I dont know how to do that, any one can help ??

    You can write any number of objects of any type into a file when you serialize them. You need to realize that once they're written to the file, they're all placed in there as type Object, so there really isn't any distinction between any of them. You don't have a file that contains only Shapes, or only Images. You write them out as Objects, and then you discover their types later as your deserialize them and read them in. You should read into the "Reflection" capabilities that all objects have. You write an Image to a file, and then a Shape, and then a Color, you can later pack these all into an ArrayList as you read them in, and when you use them discover their type using reflection.
    -Jason Thomas.

  • Trouble writing to object array

    Hi I did a semester of java 2 years ago and I'm trying to remember what I knew so please bear with me...
    I am extracting data from an xml file and then writing that information to an object array called files containing 4 string and 1 array. This files array is in turn an element in another object array containing 400 files arrays called records.
    It appeared to be working but when I want it to print out which ever record I have selected it only prints out the last record! It seems to be overwriting each files array with the next?
    Another problem I can only print out an element of the array not the entire thing?
    Please help have spent weeks on this
    Here is the code:
    Object[] Records = new Object[400];
    Object files[] = new Object[5];
    NodeList records = doc.getElementsByTagName("record");
    for( int i = 0; i < records.getLength();i++)
    Element record = (Element) records.item(i);
    NodeList headers = record.getElementsByTagName("header");
    Element header = (Element) headers.item(0);
    NodeList ids = header.getElementsByTagName("identifier");
    for(int j = 0; j < ids.getLength(); j++){
    Element id = (Element) ids.item(j);
    String ID = getText(id);
    files[0] = ID;
    NodeList metadatas = record.getElementsByTagName("metadata");
    Element metadata = (Element) metadatas.item(0);
    NodeList citeseers = metadata.getElementsByTagName("oai_citeseer:oai_citeseer");
    Element citeseer = (Element) citeseers.item(0);
    NodeList titles = citeseer.getElementsByTagName("dc:title");
    for(int k = 0; k < titles.getLength(); k++){
    Element title = (Element) titles.item(k);
    String TITLE = getText(title);
    files[1] = TITLE;
    NodeList subjects = citeseer.getElementsByTagName("dc:subject");
    for(int m = 0; m < subjects.getLength(); m++){
    Element subject = (Element) subjects.item(m);
    String SUBJECT = getText(subject);
    files[2] = SUBJECT;
    NodeList descriptions = citeseer.getElementsByTagName("dc:description");
    for(int n = 0; n < descriptions.getLength(); n++){
    Element description = (Element) descriptions.item(n);
    String DESCRIPTION = getText(description);
    files[3] = DESCRIPTION;
    String[] Names = new String[20];
    NodeList authors = citeseer.getElementsByTagName("oai_citeseer:author");
    for(int l = 0; l < authors.getLength(); l++){
    Element author = (Element) authors.item(l);
    Names[l] = author.getAttribute("name");
    files[4] = Names;
    System.out.println("The id is "+files[0]);
    System.out.println("The title is "+ files[1]);
    System.out.println("The Subject is "+ files[2]);
    System.out.println("The Description is "+ files[3]);
    for(int q=0; q < authors.getLength(); q++){
    System.out.println("The Names are "+ ((String[])files[4])[q]);
    //Records[i] = files;
    System.out.println(((Object[])Records[0])[0]);

    I'm afraid I'm not going to make you a millionaire but I feel so relieved at the moment that if I had a million I'd give it to you!!Yeah, I know you won't make me a millionaire, but I can dream... :)
    thanks for all your helpYou are welcome. Do you understand why you needed to move the creation of the "files" array.

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

  • Hot to convert a properties object to a InputStream object?

    hot to convert a properties object to a InputStream object?

    peter321 wrote:
    The two property files need further process and filter out some values. The two configuration files come from different application. I want to use java.util.logging.LogManager.readConfigure(InputStream).For the last time, you've made it clear how you want to solve some as-of-yet undescribed problem. What you haven't made clear is what problem you're trying to solve. From the class you mention, it sounds like you want to read in two logging configurations (since that's what a LogManager is for) from separate applications and "filter out some values". Those are mysterious requirements at best, and if you're intending to use LogManager to process some arbitrary properties files, you're headed down the wrong path entirely. There are [much better solutions readily available|http://commons.apache.org/configuration/].
    ~

  • Help With Writing A Vector To A File

    hi
    i am having trouble writing a vector to a file
    Here is my code
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.filechooser.*;
    public class Save
         JFileChooser fc = new JFileChooser();
         public Save(JFrame par, mainCollection col)
         try
         ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream fc.getSelectedFile().getName()));
         out.writeObject(col.carCollection);
         for(int i = 0; i< col.carCollection.size();i++)
         Cars cd = (Cars)col.carCollection.elementAt(i);
         Vector v = cd.getModels();
         out.writeObject(v);
         }catch(FileNotFoundException e){System.out.println("not found");}
         catch(IOException e){System.out.println("IO" + e.getMessage());}
    Ok now the mainCollection col is from my other class mainCollection which has my main vector in it. This main vector contains car types which contain car models i.e. Ford which contains Falcon. What i need to do is copy the whole contents of vector over in one go to the file.
    With the code above i am getting IO Exception errors
    here is the errors
    �� sr java.util.Vector��}[�;� I capacityIncrementI elementCount[ elementDatat [Ljava/lang/Object;xp       ur [Ljava.lang.Object;��X�s)l  xp  
    {sr  java.io.NotSerializableException(Vx ��5  xr java.io.ObjectStreamExceptiond��k�9��  xr java.io.IOExceptionl�sde%��  xr java.lang.Exception��>;�  xr java.lang.Throwable��5'9w�� L
    detailMessaget Ljava/lang/String;xpt Cars
    Whatever all that means
    Thanks for your help, i'm really confused
    DaJavaLodown
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Remove the for loop.
    If you write the vector, it's content will be written too.
    hi
    i am having trouble writing a vector to a file
    Here is my code
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.filechooser.*;
    public class Save
         JFileChooser fc = new JFileChooser();
         public Save(JFrame par, mainCollection col)
         try
    ObjectOutputStream out = new
    = new ObjectOutputStream(new FileOutputStream
    fc.getSelectedFile().getName()));
         out.writeObject(col.carCollection);
    for(int i = 0; i<
    = 0; i< col.carCollection.size();i++)
    Cars cd =
         Cars cd = (Cars)col.carCollection.elementAt(i);
         Vector v = cd.getModels();
         out.writeObject(v);
    }catch(FileNotFoundException
    ion e){System.out.println("not found");}
    catch(IOException e){System.out.println("IO" +
    " + e.getMessage());}
    Ok now the mainCollection col is from my other class
    mainCollection which has my main vector in it. This
    main vector contains car types which contain car
    models i.e. Ford which contains Falcon. What i need to
    do is copy the whole contents of vector over in one go
    to the file.
    With the code above i am getting IO Exception errors
    here is the errors
    �� sr java.util.Vector��}[�;� I
    capacityIncrementI elementCount[ elementDatat
    [Ljava/lang/Object;xp       ur
    r [Ljava.lang.Object;��X�s)l  xp  
    {sr  java.io.NotSerializableException(Vx ��5  xr
    java.io.ObjectStreamExceptiond��k�9��  xr
    java.io.IOExceptionl�sde%��  xr
    r java.lang.Exception��>;�  xr
    java.lang.Throwable��5'9w�� L
    detailMessaget Ljava/lang/String;xpt Cars
    Whatever all that means
    Thanks for your help, i'm really confused
    DaJavaLodown

  • File objects in jar file

    Hi!
    Is their some kind of way one can use File objects in a jar file plz? I have a project which is complete and working well on the IDE but now that I have jarred it, i've come to realize that apparently file objects do not relate well with .jar files. The problem is that the program makes a lot of file manipulations and changing everything to getResource, InputStream etc would be very lengthy. So there's absolutely no way in which one can use File objects in jar files?
    Any help would be very much appreciated!
    Thanks and regards,
    Krt_Malta

    You can use the java.net.JarURLConnection class (use file:/// when creating the URL) to get a URL to a jar entry, create a URI from the URL, and then create a File object on the URI.
    Or use java.util.jar.JarFile methods and its associated classes to get jar entry contents.
    While you can use these approaches to create File objects from a jar, they are not any easier than what's already been mentioned.
    And all you can do is read or delete a jar - jar entries can't be rewritten.

  • Saving An Object to a File

    I'm writing a group of Classes that handles manipulation of Plasmids (basically circular DNA sequences). My problem is that I want to save the objects to a file. I've been able to implement something that kindof works but has some problems. First what I have so far.
    public static Plasmid getPlasmidFromFile(File path) throws FileNotFoundException, IOException, ClassNotFoundException {
            FileInputStream fileIn = new FileInputStream(path);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            return (Plasmid)in.readObject();
    public void savePlasmidToFile(File path) throws IOException {
            FileOutputStream fileOut = new FileOutputStream(path);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(this);
            out.close();
        }Now this works perfectly except for one thing. As part of the plasmid object there is two arrays of objects (Origin and Gene).
    Gene genes[] = new Gene[MAX_GENES];
    Origin origins[] = new Origin[MAX_ORIGINS];When I use my getPlasmidFromFile() method to load a file it does not load genes[] or origins[]. Both Origin and Gene implements java.io.Serializable (well and Plasmid).
    Any insight into what I'm doing wrong? Thanks in advance for any help.

    Thanks guys for your quick responses. Realized I was
    doing something really stupid.
    Niether Origin or Gene was declared static.
    However, both of them were extended from the Class
    DNASequenceOfInterest and that Class was not declared
    Serilalizable. Implementing that there fixed my
    problems. I've been trying to fix this sense last
    night with no success and now I just feel stupid :/Happens to all of us! At least you figured it out on your own.

  • Writing serialized objects as XML

    What are the advantages and a disadvantages for writing serialized objects as XML instead of the Java binary format?

    Depending on the serialization scheme, XML can be used to loosely bind the persistant data, so that the class can change version, or even be replaced by a different class as the project requires refactoring over its lifecycle.
    It also allows non-Java tools to interact with your data, which almost always has a longer lifetime than any implementation. I still occasionally process SGML files from the '80s. If they had been in a proprietory binary format, that data would be far harder to re-use.
    Pete

  • Error while updating DocumentDefinition AIP-11052:Writing following objects

    Hi All,
    I am getting this error while updating ecs in Document Definition. I was able to do it properly on the same environment a few weeks back but now its throwing an error:
    Error -: AIP-11052: Writing following objects: Document Definition failed due to following constraint violation: DOCUMENTDEFINITION. CAN NOT UPDATE UNVERSIONABLE OBJECT IN A VALIDATED CONFIGURATION
    I read in some of the OTN forums that this may be an environment issue. So i restarted the B2B server as suggested but the error seems to still exist.
    Kindly reply how to proceed. Its little critical.
    Thanks in advance.

    Make sure there is no agreement in deployed/validated state which is using this document definition. Retire and purge all existing configurations which are using this doc def and make sure there is no agreement in validated state. If there is an agreement in validated state and then change/just update anything in agreement and save it to bring it back into draft state.
    Regards,
    Anuj

  • Problem on reading and writing from from a *.txt file

    I get Problem on reading and writing from from a *.txt file. The following is the read() method...
    The software said the DataInputStream is depreciated. Can anyone help me please?
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        String str = "";
        try
          in = new BufferedReader(file);
          //in = new FileInputStream(file);
          for(;;)
            str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);
      }

    Thank you for your reply. I have made some change. However, there is an incompetable type found error.
    in = new BufferedReader(new InputStreamReader(in));The following are all of the code.
    public void read()
        File file = new File("C://Documents and Settings//Charles//My Documents//Brunel//EE2065//Assignment and Lab//Assignment 4 and Lab 4//data.txt");
        FileInputStream in = null;
        //BufferedReader in = null;
        String str = "";
        try
          in = new BufferedReader(new InputStreamReader(in));
          //in = new FileInputStream(file);
          for(;;)
            BufferedReader Bstr = new BufferedReader(new InputStreamReader(in));
            //str = new BufferedReader(in).readLine();
            //str = new DataInputStream(in).readLine();
            if(str == null)
              break;
            System.out.print(str);
        in.close();
        catch(IOException e)
            System.err.println("execution error: " +e);

  • Writing HTML data in TEXT File

    I am writing HTML content in TEXT file ...I read it in a string and then write using PrintStream...
    But it writes all content on one line ..I want to write it as it was in source HTML file...

    Perchance, the OP is referring to the lack of carriage returns in his outputted data, and querying where they have absconded to? An analysis of his posts to date reveals that he has read the contents of a File into a String variable, and wants to write the (presumably modified) String back to a file (uncertain as to whether this is the same file or a different one) In the process of outputting to said file, carriage returns previously contained in the original input file are not present in the output. I would hazard a guess that the OP does not want said carriage returns in the String to disappear.
    Is my analysis of the situation correct?
    An example of the code that you have written to date would be of extreme usefulness to us in aiding you in your noble quest.
    Without such a resource, I must rely on my intuition instead.
    Possible places that the carriage returns are being "dropped"
    1 - On reading in. Are you discarding carriage returns while building up your variable?
    2 - On manipulating. Are you processing this line by line, or reading it all into one large variable?
    3 - On output - are you using "print" or "println" in the output?
    I look forward to further correspondence with you sir
    kind regards,
    evnafets

  • Save different Objects in one file by two different streams

    Hi all,
    I have a issue to read two Objects from one file if I write those in two different streams.
    I open the ObjectOutputStream and save an Object to the file. Then I close this stream and file. Then I open the new ObjectOutputStream and save the second Object in the same file. It works Ok. Then I open the ObjectInputStream and try to read those two objects and get java.io.StreamCorruptedException.
    This exception happes only when app tryes to read the second Object.
    this is the code example:
    //Write part
    for (int i=0;i<2;i++)
    File file = new File("test.swp");
    FileOutputStream fileOut = new FileOutputStream(file,true);
    ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
    JobObject jobObj = new JobObject();
    jobObj.setID(i);
    objOut.writeObject(jobObj);
    objOut.flush();
    objOut.close();
    fileOut.close();
    //Read part
    FileInputStream fileOut = new FileInputStream("test.swp");
    ObjectInputStream objOut = new ObjectInputStream(fileOut);
    for (int i=0;i<2;i++)
    JobObject jobObj = (JobObject)objOut.readObject();
    objOut.close();
    fileOut.close();
    Thank for any help.

    Maybe try closing the ObjectInputStream (and re-creating it as needed) within your for loop?
    - Saish
    "My karma ran over your dogma." - Anon

Maybe you are looking for