Saving an object into  a file

Hey all,
I'm trying to save an object I have coded to a file on my hard-drive
using an inner save() method.
Though I realise I should put something in an output stream,
I can't find a way to put my object into an input-stream. How do I do that? Using which classes?

to save an object's state use: implements serializable
http://java.sun.com/docs/books/tutorial/essential/io/objectstreams.html

Similar Messages

  • Saving multiples objects into a file

    I want to create a single file that has multiples things inside, like pictures (png) and texts. Does someone knows how it will be the structure of the binary file?
    I'm programming a draw software like photoshop, where my layers are BufferedImages. Theses bufferedImages must be saved into a file to re-open later and edit.
    Please I want just ideas....
    thanks

    If the objects that you store in your file are fairly independent of each other, one thing that comes
    to mind is to make your file a zip file of component files. That way you can use standard tools to examine
    it and edit it if you wish.
    Another thing to note is that if your file is largely a series of images, some image file formats,
    like tiff , jpeg and gif allow you to store sequences of images in one file.
    Here's a demo that creates a tiff file holding four images, then reads the file and displays the images.
    Stardard software like Kodak's "Imaging Preview" will allow you to flip through the images in the file.
    By the way, if you don't have readers/writers for format tiff, you can get them here.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class IOExample {
        public static void main(String[] args) throws IOException {
            String urlPrefix = "http://www3.us.porsche.com/english/usa/carreragt/modelinformation/experience/desktop/bilder/icon";
            String urlSuffix = "_800x600.jpg";
            int SIZE = 4;
            BufferedImage[] images = new BufferedImage[SIZE];
            for(int i=1; i<=SIZE; ++i)
                images[i-1] = ImageIO.read(new URL(urlPrefix + i + urlSuffix));
            File file = new File("test.tiff");
            file.delete();
            int count = writeImages(images, file);
            if (count < SIZE)
                throw new IOException("Only " + count + " images written");
            images = null;
            images = readImages(file);
            if (images.length < SIZE)
                throw new IOException("Only " + images.length + " images read");
            display(images);
        public static void display(BufferedImage[] images) {
            JFrame f = new JFrame("IOExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel(new GridLayout(0,1));
            for(int j=0; j<images.length; ++j) {
                JLabel label = new JLabel(new ImageIcon(images[j]));
                label.setBorder(BorderFactory.createEtchedBorder());
                p.add(label);
            f.getContentPane().add(new JScrollPane(p));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        //suffix is "jpeg", "gif", "png", etc... according to your service providers
        public static ImageWriter getWriter(String suffix) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix(suffix);
            if (!writers.hasNext())
                throw new IOException("no writers for suffix " + suffix);
            return (ImageWriter) writers.next();
        public static ImageReader getReader(String suffix) throws IOException {
            Iterator readers = ImageIO.getImageReadersBySuffix(suffix);
            if (!readers.hasNext())
                throw new IOException("no reader for suffix " + suffix);
            return (ImageReader) readers.next();
        public static int writeImages(BufferedImage[] sources, File destination) throws IOException {
            if (sources.length == 0) {
                System.out.println("Sources is empty!");
                return 0;
            } else {
                ImageWriter writer = getWriter(getSuffix(destination));
                ImageOutputStream out = ImageIO.createImageOutputStream(destination);
                writer.setOutput(out);
                writer.prepareWriteSequence(null);
                for(int i=0; i<sources.length; ++i)
                    writer.writeToSequence(new IIOImage(sources, null, null), null);
    writer.endWriteSequence();
    return sources.length;
    public static BufferedImage[] readImages(File source) throws IOException {
    ImageReader reader = getReader(getSuffix(source));
    ImageInputStream in = ImageIO.createImageInputStream(source);
    reader.setInput(in);
    ArrayList images = new ArrayList();
    GraphicsConfiguration gc = getDefaultConfiguration();
    try {
    for(int j=0; true; ++j)
    images.add(toCompatibleImage(reader.read(j), gc));
    } catch(IndexOutOfBoundsException e) {
    return (BufferedImage[]) images.toArray(new BufferedImage[images.size()]);
    public static String getSuffix(File file) throws IOException {
    String filename = file.getName();
    int index = filename.lastIndexOf('.');
    if (index == -1)
    throw new IOException("No suffix given for file " + file);
    return filename.substring(1+index);
    //make compatible with gc for faster rendering
    public static BufferedImage toCompatibleImage(BufferedImage image, GraphicsConfiguration gc) {
    int w = image.getWidth(), h = image.getHeight();
    int transparency = image.getColorModel().getTransparency();
    BufferedImage result = gc.createCompatibleImage(w, h, transparency);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
    public static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();

  • Saving business objects into xml file

    I have the following XML file parsed into a DOM tree, with 2 different types of nodes "TestCase" and
    "RealCase". Then I mapped each type to a different type of business object, TestCaseObj and RealCaseObj.
    Now, there may be addition of new objects, or modifications to the data stored in the business objects
    by my application. Eventually when I save the business objects back into the XML file, how should I go
    about doing that?
    <ROOT>
    <TestCase TestID="T1">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
    </TestCase>
    <TestCase TestID="T2">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
    </TestCase>
    <RealCase ID="R1">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
         <Element3>Data3</Element3>
    </RealCase>
    <RealCase ID="R2">
         <Element1>Data1</Element1>
         <Element2>Data2</Element2>
         <Element3>Data3</Element3>
    </RealCase>
    </ROOT>

    The DocumentBuilder class does not allow you to parse a portion of the xmlfile. Therefore, it will not be possible to read "TestCase" into the DOM without bringing in "RealCase" nodes as well. As such, these codes will parse the entire xml file into DOM:
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse( xmlFile );
    However, your problem can be solved by reading only "TestCase" nodes in DOM, as follows:
    NodeList elementNodeList =
    elementNode.getElementsByTagName("TestCase");
    Your codes will then change the data in the elementNodeList, without affecting "RealCase" although it is loaded into DOM. You can be sure that elementNodeList contains only "TestCase" nodes.
    Once you have made your changes, save the DOM back to the XML file, using the serializer method as discussed earlier.
    Good luck.

  • I received pictures in a dozen emails and saved each picture into one file in .pages.  I did not import the photos before doing this and now iPhoto won't recognize the pictures because they are in a .pages file.  How do I get the pics to iPhoto?

    I received a dozen pictures in a few emails and I saved them all into one file in pages.  I just copied and pasted.  I do not have the originals any longer.  Iphoto will not permit me to import the pictures as it does not recognize a .pages file, nor can I simply click and drag from the pages document to iphoto nor from pages to the desktop to iphoto.  How can I save each picture I guess back into a jpeg and then import them into iphoto or have i lost them to a pages document forever?  This is urgent as I need the pictures made into a book on iphoto for work by Friday!!!  Please advise!  Thank you.

    Greetings,
    Locate the Pages document wherever it's located on your computer and click once on it to highlight it.
    Go to File > Duplicate to make a backup copy of the file.
    Click once again on the file to highlight it.
    Go to File >  Get Info
    In the "Name & Extension" category remove the ".pages" extension and put in ".zip".
    Close the info window and double-click the now renamed pages file (zip file now).It will decompress into a folder which contains all the base components including all the images you added.  These can be dragged onto the iPhoto icon to import them.
    Hope that helps.

  • Converting Document object into XML file

    I was wondering how to convert a document object to XML file? I have read the documentation about document and Node but nothing explains the procedure of the conversion. Ive been told that it can be done, but not sure how. I have converted an XML file into Document by parsing DocumentBuilder. Just not sure how to do the reverse. Any help appreciated.

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer trans = tf.newTransformer();
    trans.transform(new DOMSource(yourDOMsRootNode), new StreamResult(new FileOutputStream(yourFileName)));or something a lot like that.

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

  • Saving each layer into a file?

    Hello everyone,
    I need to take each layer's data and save it into a file. How would I retrieve individual layer's image data?
    Thanks

    The ReadLayerDesc and associated callbacks ARE how you get the color data and opacity for each layer.
    And layers don't have alpha channels - those belong to the document.
    (sounds like you are confusing opacity with alpha channels)

  • How can we create a ABAP object into .ptr file

    HI,
          How can we create a ABAP object into .ptr/.car/.sar format so that we can give it to a remote client and which can be imported into their R/3 system to get the functionality of this object.

    Hello Ramesh
    All you need is SAPLINK. Have a look at the following links:
    <a href="/people/ed.herrmann/blog/2005/11/14/the-enterprise-and-the-bazaar Enterprise and the Bazaar</a>
    <a href="https://sourceforge.net/projects/saplink/">SAPLINK</a>
    Regards
      Uwe

  • Export Oracle Databaes Objects into sql file

    Hi Experts,
    I searched and could not find anything whether is that possible to dump oracle database into a sql file.
    Can some one clarify this?
    Thanks,
    Dharan V

    Hi,
    Still struggling here,
    CREATE OR REPLACE DIRECTORY DUMP_DIR AS 'c:\';
    GRANT DATAPUMP_EXP_FULL_DATABASE TO SCOTT;
    GRANT DATAPUMP_IMP_FULL_DATABASE TO SCOTT;
    EXPDP SCOTT@LOCAL-DB directory=DUMP_DIR dumpfile=scott.dmp content=metadata_only Full=Y
    password: tiger
    C:\Documents and Settings\Dharan>expdp SCOTT@LOCAL-DB directory=DUMP_DI
    R dumpfile=scott.dmp content=metadata_only Full=Y
    Export: Release 11.1.0.6.0 - Production on Sunday, 31 January, 2010 16:48:42
    Copyright (c) 2003, 2007, Oracle.  All rights reserved.
    Password:
    Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Produc
    tion
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Starting "SCOTT"."SYS_EXPORT_FULL_01":  SCOTT/********@LOCAL-DB directo
    ry=DUMP_DIR dumpfile=scott.dmp content=metadata_only Full=Y
    Processing object type DATABASE_EXPORT/TABLESPACE
    Processing object type DATABASE_EXPORT/PROFILE
    Processing object type DATABASE_EXPORT/SYS_USER/USER
    Processing object type DATABASE_EXPORT/SCHEMA/USER
    Processing object type DATABASE_EXPORT/ROLE
    Processing object type DATABASE_EXPORT/GRANT/SYSTEM_GRANT/PROC_SYSTEM_GRANT
    Processing object type DATABASE_EXPORT/SCHEMA/GRANT/SYSTEM_GRANT
    Processing object type DATABASE_EXPORT/SCHEMA/POST_SCHEMA/PROCACT_SCHEMA
    Processing object type DATABASE_EXPORT/AUDIT
    Master table "SCOTT"."SYS_EXPORT_FULL_01" successfully loaded/unloaded
    Dump file set for SCOTT.SYS_EXPORT_FULL_01 is:
      C:\SCOTT.DMP
    Job "SCOTT"."SYS_EXPORT_FULL_01" successfully completed at 16:51:20But i don't see any scott.dmp in either c:\ [on newly created directory]
    OR C:\Documents and Settings\Dharan.
    Ok...i Tried similarly the second one now
    C:\Documents and Settings\Dharan>impdp SCOTT@LOCAL-DB directory=DUMP_DI
    R dumpfile=scott.dmp content=metadata_only Full=Y
    Export: Release 11.1.0.6.0 - Production on Sunday, 31 January, 2010 16:48:42
    Copyright (c) 2003, 2007, Oracle.  All rights reserved.
    Password:
    Connected to: Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Produc
    tion
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Master table "SCOTT"."SYS_SQL_FILE_FULL_01" successfully loaded/unloaded
    Starting "SCOTT"."SYS_SQL_FILE_FULL_01":  SCOTT/********@LOCAL-DB dire
    tory=DUMP_DIR dumpfile=scott.dmp SQLFILE=SCOTT.sql
    Processing object type DATABASE_EXPORT/TABLESPACE
    Processing object type DATABASE_EXPORT/PROFILE
    Processing object type DATABASE_EXPORT/SYS_USER/USER
    Processing object type DATABASE_EXPORT/SCHEMA/USER
    Processing object type DATABASE_EXPORT/SCHEMA/TABLE/POST_INSTANCE/PROCDEPOBJ
    Processing object type DATABASE_EXPORT/SCHEMA/POST_SCHEMA/PROCOBJ
    Processing object type DATABASE_EXPORT/SCHEMA/POST_SCHEMA/PROCACT_SCHEMA
    Processing object type DATABASE_EXPORT/AUDIT
    Job "SCOTT"."SYS_SQL_FILE_FULL_01" successfully completed at 17:13:35Even now i can't see any .sql file either c:\ [on newly created directory]
    OR C:\Documents and Settings\Dharan.
    Suggest what am doing wrong here.
    Thanks,
    Dharan V

  • Saving multiple records into text file

    Can I save multiple records into a text file at one go?
    My application has a list of data displayed there and when the user clicks on the save button it will save all the records on the screen.
    It works but it only saves the last record.
    Here are my codes
    // this is to display the list of data
    private JLabel[] subjects=new JLabel[20];
    private JLabel[] subTotal=new JLabel[20];
    private JLabel[] codes=new JLabel[20];
    private JLabel[] getTotal=new JLabel[20];
    String moduleCodes;
    String getPrice;
    double price;
    int noOfNotes;
    public testapp(Subjects[] subList)
    int j=0;
                double CalTotal=0;
              for (int i=0; i<subList.length; i++)
                   subjects[i] = new JLabel();
                   subTotal[i] = new JLabel();
                   codes=new JLabel();
                   getTotal[i]=new JLabel();
                   if (subList[i].isSelected)
                        System.out.println(i+"is selected");
                        subjects[i].setText(subList[i].title);
                        subjects[i].setBounds(30, 140 + (j*30), 400, 40);
                        subTotal[i].setText("$"+subList[i].price);
                        subTotal[i].setBounds(430,140+(j*30),100,40);
                        codes[i].setText(subList[i].code);
                        getTotal[i].setText(subList[i].price+"");
                        CalTotal+=subList[i].price;
                        contain.add(subjects[i]);
                        contain.add(subTotal[i]);
                        j++;
                        moduleCodes=codes[i].getText();                              
                        getPrice=getTotal[i].getText();
                        noOfNotes=1;
    // this is where the records are saved
         public void readRecords(String moduleCodes,String getPrice,int notes)throws IOException
              price=Double.parseDouble(getPrice);
              String outputFile = "testing.txt";
              FileOutputStream out = new FileOutputStream(outputFile, true);      
         PrintStream fileOutput = new PrintStream(out);
              SalesData[] sales=new SalesData[7];
              for(int i=0;i<sales.length ;i++)
                   sales[i]=new SalesData(moduleCodes,price,notes);
                   fileOutput.println(sales[i].getRecord());
              out.close();

    I suggest writing a method that takes a SalesData[]
    parameter and a filename. Example:
    public void writeRecords(SalesData[] data,
    String filename) throws IOException
    BufferedWriter out = new BufferedWriter(new
    FileWriter(filename, true));
    for (int i = 0; i < data.length; i++)
    out.write(data.getRecord());
    out.newLine();
    out.close();
    And it's good to get in the habit of doing things like closing resources in finally blocks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • Trouble importing objects into existing file

    I have Captivate 4 and would like to import slides/objects from file 1 to file 2.
    Everytime I do this, captivate crashes and says that it has encountered an unexpected error. It is driving me crazy,
    especially since it's not like I can copy and paste in the program. Or can I? Please help.

    Fortunately I haven't had a corrupted file or project for some time now. I put it down to never working on project files over a network and never pasting in content from other people's projects.
    But the way I used to track down corrupt elements or slides was to Save As to get a copy of my problem project and then hide or delete half the slides in the project to see if that removed the problem. If not, I try hiding or deleting the other half of the project to see if that worked.  If you find the half that has the problem, then delete half of that half and repeat the process.  Eventually, by a process of elimination, you get down to where the issue is.  Then you can go back to your main project and fix it.  Hopefully it's just a matter of recreating a slide or two.

  • Converting Dom Document object into XML file removes the DTD

    Hi All
    My xml is dtd. I have one xml file. i changed the node value after that i want to create a xml file with the same name. I created new xml file but i am not seeing the old dtd in the new file. This process is done with the help of jaxp.
    My code is given below
    File fileInput = new File("input.xml");
              File fileOutput = new File("output.xml");
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setExpandEntityReferences(false);
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(fileInput);
              TransformerFactory tFactory = TransformerFactory.newInstance();
              Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "true");
              transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
              DOMSource source = new DOMSource(document);
              FileOutputStream fos = new FileOutputStream(fileOutput);
              StreamResult result = new StreamResult(fos);
              transformer.transform(source, result);
    Thanks in advance

    The Transformer API does not guarantee the preservation of that information. You may want to check the DOM L3 Load/Save package (http://java.sun.com/javase/6/docs/api/index.html). Alternatively, you may force things by setting the additional output properties 'doctype-public' and 'doctype-system'.

  • Extract Roles (DB Object ) into separate files in Oracle

    Hi all,
    Help needed in extraction of Oracle Roles in a File (Text) through a script where I can basically extract all the Oracle Roles to a file from a given schema
    Thanks in Advance,
    Anurag.

    Do the following at sql prompt
    sql> spool roles.txt
    sql> select role from dba_roles;
    sql> spool off

  • Problem with data saving into text file

    Hi,
    The problem I am facing wihile saving the data into text file is that everytime when I am slecting the path from front panel, the data which is being saved is appended with the previous data, i.e. not only in the new text file, the new set of data is saved but also, if there is any previuos run for the program, the corresponding data is also present in that text file.
    However, when I change the same 'control'(file path) to 'constant' in the block diagram, and add the file path, there is no such problem. Basically, changing the "File path" from constant in the block diagram to control (so that it is displayed in the front panel) is causing the problem.
    Please help!
    Thanks 
    Solved!
    Go to Solution.
    Attachments:
    front panel.JPG ‏222 KB
    Block Diagram.JPG ‏70 KB
    Block diagram with File Path as Constant.JPG ‏74 KB

    Your shift register on the For loop is not initialized. It will retain the value of the string from the last time it executed. Initialize that and it should solve your problem.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot

Maybe you are looking for