Here you can find the source of saveToFile(File f, Object obj)
public static void saveToFile(File f, Object obj) throws IOException
//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(); } }