Java ObjectOutputStream Write saveToFile(File f, Object obj)

Here you can find the source of saveToFile(File f, Object obj)

Description

save To File

License

Apache License

Declaration

public static void saveToFile(File f, Object obj) throws IOException 

Method Source Code

//package com.java2s;
/*//www.j  av a2  s . c  om
 * Copyright (C) 2015 The 8-Bit Bunch. Licensed under the Apache License, Version 1.1 
 * (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-1.1>.
 * 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.ByteArrayOutputStream;
import java.io.File;

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

import java.io.ObjectOutputStream;

import java.util.zip.Deflater;

public class Main {
    public static void saveToFile(File f, Object obj) throws IOException {
        try (FileOutputStream fis = new FileOutputStream(f, false)) {
            fis.write(compress(objectToByte(obj)));
            fis.flush();
            fis.close();
        }
    }

    public static byte[] compress(byte[] bytesToCompress) {
        Deflater deflater = new Deflater();
        deflater.setInput(bytesToCompress);
        deflater.finish();
        byte[] bytesCompressed = new byte[Short.MAX_VALUE];
        int numberOfBytesAfterCompression = deflater.deflate(bytesCompressed);
        byte[] returnValues = new byte[numberOfBytesAfterCompression];
        System.arraycopy(bytesCompressed, 0, returnValues, 0, numberOfBytesAfterCompression);
        return returnValues;
    }

    public static byte[] objectToByte(Object o) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ObjectOutputStream os = new ObjectOutputStream(out)) {
            os.writeObject(o);
            os.flush();
            os.close();
        }
        return out.toByteArray();
    }
}

Related

  1. saveResultToStream(ObjectOutputStream oos, Object result)
  2. saveResultToStream(ObjectOutputStream oos, Object result)
  3. saveSerializableObject(Object obj, String path)
  4. saveSerialized(Serializable obj, File file)
  5. saveStringToFile(String filepath, String content)
  6. saveToFile(final File file, final Object obj)
  7. saveToFile(Serializable object, File file, boolean compress)
  8. saveToFile(String string, File file, boolean append)