Java Object Save writeObjectToFile(Object o, String fileName)

Here you can find the source of writeObjectToFile(Object o, String fileName)

Description

Serialize java object to a file.

License

Apache License

Parameter

Parameter Description
o the java object
fileName the name of the file

Exception

Parameter Description
IOException if io problems

Return

the file

Declaration

public static File writeObjectToFile(Object o, String fileName) throws IOException 

Method Source Code

//package com.java2s;
/*/*w w w  .j a va  2  s.  co  m*/
 *  Copyright 2016 Rodrigo Agerri
    
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
    
   http://www.apache.org/licenses/LICENSE-2.0
    
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import java.io.ObjectOutputStream;
import java.io.OutputStream;

import java.util.zip.GZIPOutputStream;

public class Main {
    /**
     * Serialize java object to a file.
     * @param o the java object
     * @param fileName the name of the file
     * @return the file
     * @throws IOException if io problems
     */
    public static File writeObjectToFile(Object o, String fileName) throws IOException {
        File outFile = new File(fileName);
        OutputStream outputStream = new FileOutputStream(outFile);
        if (fileName.endsWith(".gz")) {
            outputStream = new GZIPOutputStream(outputStream);
        }
        outputStream = new BufferedOutputStream(outputStream);
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(o);
        oos.close();
        return outFile;
    }
}

Related

  1. writeObjectToFile(File file, Object o)
  2. writeObjectToFile(File file, Object obj)
  3. writeObjectToFile(final Object o, final File dir)
  4. writeObjectToFile(Object o, File file, boolean append)
  5. writeObjectToFile(Object o, String filename)
  6. writeObjectToFile(Object obj, File f)
  7. writeObjectToFile(Object obj, String fileName)
  8. writeObjectToFile(Object obj, String path)
  9. writeObjectToFile(Object object, File file)