Java Code Examples for java.io.ObjectInputStream#close()

The following examples show how to use java.io.ObjectInputStream#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestDateMidnight_Basics.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testSerialization() throws Exception {
    DateMidnight test = new DateMidnight(TEST_TIME_NOW_UTC);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(test);
    byte[] bytes = baos.toByteArray();
    oos.close();
    
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);
    DateMidnight result = (DateMidnight) ois.readObject();
    ois.close();
    
    assertEquals(test, result);
}
 
Example 2
Source File: StarRater.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts a byte array to an image that has previously been converted with imageToCompressedByteArray(Image image).
 * The image is not recognizable as image from standard tools.
 *
 * @param data  The image.
 * @return  The image.
 */
public static Image compressedByteArrayToImage(byte[] data) {
  try {
    // unzip data
    ByteArrayInputStream byteStream = new ByteArrayInputStream(data);
    GZIPInputStream zippedStream = new GZIPInputStream(byteStream);
    ObjectInputStream objectStream = new ObjectInputStream(zippedStream);
    int width = objectStream.readShort();
    int height = objectStream.readShort();
    int[] imageSource = (int[])objectStream.readObject();
    objectStream.close();

    // create image
    MemoryImageSource mis = new MemoryImageSource(width, height, imageSource, 0, width);
    return Toolkit.getDefaultToolkit().createImage(mis);
  }
  catch (Exception e) {
    return null;
  }
}
 
Example 3
Source File: ObjectPoolStack.java    From tlaplus with MIT License 6 votes vote down vote up
public void run() {
    try {
        synchronized(this) {
            while (true) {
                while (ObjectPoolStack.this.poolFile == null) {
                    this.wait();
                }
                ObjectInputStream ois = FileUtil.newOBFIS(ObjectPoolStack.this.poolFile);
                for (int i = 0; i < ObjectPoolStack.this.buf.length; i++) {
                    ObjectPoolStack.this.buf[i] = ois.readObject();
                }
                ois.close();
                ObjectPoolStack.this.poolFile = null;
                ObjectPoolStack.this.isIdle = true;
                ObjectPoolStack.this.notify();	    
            }
        }
    }
    catch (Exception e) 
    {
        MP.printError(EC.SYSTEM_ERROR_WRITING_POOL, e);
        System.exit(1);
    }
}
 
Example 4
Source File: TopComponentTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Test of readExternal method, of class org.openide.windows.TopComponent.
 */
public void testOldReadExternal() throws Exception {
    TopComponent tc = null;
    try {
        ObjectInputStream stream = new ObjectInputStream(
                getClass().getResourceAsStream("data/oldTcWithoutDisplayName.ser"));
        tc = (TopComponent)stream.readObject();
        stream.close();
    } catch (Exception exc) {
        exc.printStackTrace();
        fail("Cannot read tc");
    }
    
    
    assertNotNull("One again", tc);
    assertEquals("testName", tc.getName());
    assertEquals("testTooltip", tc.getToolTipText());
    assertEquals("If the old component does not have a display name, then keep it null", null, tc.getDisplayName());
}
 
Example 5
Source File: RowIdTransporter.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Transforms a serialized Base 64 String to a java.sql.Array.
    * 
    * @param s
    *            a serialized java.sql.Array in Base64 format
    * @return the rebuilt java.sql.Array
    * @throws IOException
    * @throws ClassNotFoundException
    */
   public RowId fromBase64(String s)
    throws IOException, ClassNotFoundException {

byte[] byteArray = Base64.base64ToByteArray(s);
ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);

ObjectInputStream ois = new ObjectInputStream(bis);

RowId rowId = null;
try {
    rowId = (RowId) ois.readObject();
    return rowId;
} finally {
    if (ois != null) {
	ois.close();
    }
}
   }
 
Example 6
Source File: SimpleSerialization.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final Vector<String> v1 = new Vector<>();

    v1.add("entry1");
    v1.add("entry2");

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(baos);

    oos.writeObject(v1);
    oos.close();

    final byte[] data = baos.toByteArray();
    final ByteArrayInputStream bais = new ByteArrayInputStream(data);
    final ObjectInputStream ois = new ObjectInputStream(bais);

    final Object deserializedObject = ois.readObject();
    ois.close();

    if (false == v1.equals(deserializedObject)) {
        throw new RuntimeException(getFailureText(v1, deserializedObject));
    }
}
 
Example 7
Source File: TemplateSelection.java    From fnlp with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void printAccuracyRecords(String serfile)
		throws FileNotFoundException, IOException, ClassNotFoundException {
	ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
			serfile));
	Map<Integer, Double> AccuracyRecords = (Map<Integer, Double>) ois
			.readObject();
	ois.close();
	printAccuracyRecords(AccuracyRecords);
}
 
Example 8
Source File: Serializer.java    From JANNLab with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads an object from a file. The instance if casted automatically.
 * <br></br>
 * @param filename Source filename.
 * @return Instance of the persisted object.
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static <T> T read(final String filename) throws IOException, ClassNotFoundException {
    //
    File file = new File(filename);
    //
    ObjectInputStream in = new ObjectInputStream(
        new GZIPInputStream(new FileInputStream(file))
    );
    //
    @SuppressWarnings("unchecked")
    T obj = (T)in.readObject();
    in.close();
    return obj;
}
 
Example 9
Source File: JavaUtils.java    From Robust with Apache License 2.0 5 votes vote down vote up
public static Object getMapFromZippedFile(String path) {
    File file = new File(path);
    Object result = null;
    try {
        if (file.exists()) {
            FileInputStream fileIn = new FileInputStream(file);
            GZIPInputStream gzipIn = new GZIPInputStream(fileIn);
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            int count;
            byte[] data = new byte[1024];
            while ((count = gzipIn.read(data, 0, 1024)) != -1) {
                byteOut.write(data, 0, count);
            }
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(byteIn);
            result = oi.readObject();
            fileIn.close();
            gzipIn.close();
            oi.close();
        } else {
            throw new RuntimeException("getMapFromZippedFile error,file doesn't exist ,path is " + path);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("getMapFromZippedFile from " + path + "  error ");
    }
    return result;
}
 
Example 10
Source File: WheelAreaPicker.java    From WheelPicker with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<Province> getJsonDataFromAssets(AssetManager assetManager) {
    List<Province> provinceList = null;
    try {
        InputStream inputStream = assetManager.open("RegionJsonData.dat");
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        provinceList = (List<Province>) objectInputStream.readObject();
        objectInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return provinceList;
}
 
Example 11
Source File: SerializerUtils.java    From Cubert with Apache License 2.0 5 votes vote down vote up
public static Object deserializeFromBytes(byte[] bytes) throws IOException,
        ClassNotFoundException
{
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

    ObjectInputStream ois = new ObjectInputStream(bis);
    Object obj = ois.readObject();
    ois.close();

    return obj;
}
 
Example 12
Source File: RecentEmojiManager.java    From yykEmoji with Apache License 2.0 5 votes vote down vote up
public Collection getCollection(String key) throws IOException, ClassNotFoundException {
    String collectionString = getString(key);
    if (TextUtils.isEmpty(collectionString) || TextUtils.isEmpty(collectionString.trim())){
        return null;
    }
    byte[] mobileBytes = Base64.decode(collectionString.getBytes(), Base64.DEFAULT);
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(mobileBytes);
    ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    Collection collection = (Collection) objectInputStream.readObject();
    objectInputStream.close();
    return collection;
}
 
Example 13
Source File: Linear.java    From fnlp with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param file
 * @return
 * @throws LoadModelException
 */
public static Linear loadFrom(String file) throws LoadModelException {
	Linear cl;
	try {
		ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(
				new BufferedInputStream(new FileInputStream(file))));
		cl = (Linear) in.readObject();
		in.close();
	} catch (Exception e) {
		throw new LoadModelException("分类器读入错误");
	}
	return cl;
}
 
Example 14
Source File: KNN.java    From fnlp with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *  从文件读入分类器
 * @param file
 * @return
 * @throws LoadModelException
 */
public static KNN loadFrom(String file) throws LoadModelException{
	KNN cl = null;
	try {
		ObjectInputStream in = new ObjectInputStream(new GZIPInputStream(
				new BufferedInputStream(new FileInputStream(file))));
		cl = (KNN) in.readObject();
		in.close();
	} catch (Exception e) {
		throw new LoadModelException(e,file);
	}
	return cl;
}
 
Example 15
Source File: AddressNameConverter.java    From Lunary-Ethereum-Wallet with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public synchronized void load(Context context) throws IOException, ClassNotFoundException {
    FileInputStream fout = new FileInputStream(new File(context.getFilesDir(), "namedb.dat"));
    ObjectInputStream oos = new ObjectInputStream(new BufferedInputStream(fout));
    addressbook = (HashMap<String, String>) oos.readObject();
    oos.close();
    fout.close();
}
 
Example 16
Source File: StreamServer.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
private static StreamSplit getStreamSplit(InputStream inputStream) throws IOException {
  Tracer tracer = Trace.trace("stream - getStreamSplit");
  ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
  try {
    return (StreamSplit) objectInputStream.readObject();
  } catch (ClassNotFoundException e) {
    throw new IOException(e);
  } finally {
    objectInputStream.close();
    tracer.done();
  }
}
 
Example 17
Source File: Main.java    From TelegramChat with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onEnable() {
	this.saveDefaultConfig();
	cfg = this.getConfig();
	Utils.cfg = cfg;

	Bukkit.getPluginCommand("telegram").setExecutor(new TelegramCmd());
	Bukkit.getPluginCommand("linktelegram").setExecutor(new LinkTelegramCmd());
	Bukkit.getPluginManager().registerEvents(this, this);

	File dir = new File("plugins/TelegramChat/");
	dir.mkdir();
	data = new Data();
	if (datad.exists()) {
		try {
			FileInputStream fin = new FileInputStream(datad);
			ObjectInputStream ois = new ObjectInputStream(fin);
			Gson gson = new Gson();
			data = (Data) gson.fromJson((String) ois.readObject(), Data.class);
			ois.close();
			fin.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	telegramHook = new Telegram();
	telegramHook.auth(data.getToken());

	Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
		boolean connectionLost = false;
		if (connectionLost) {
			boolean success = telegramHook.reconnect();
			if (success)
				connectionLost = false;
		}
		if (telegramHook.connected) {
			connectionLost = !telegramHook.getUpdate();
		}
	}, 10L, 10L);

	new Metrics(this);
}
 
Example 18
Source File: AbstractHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Deserialize a RemoteInvocationResult object from the given InputStream.
 * <p>Gives {@code decorateInputStream} a chance to decorate the stream
 * first (for example, for custom encryption or compression). Creates an
 * {@code ObjectInputStream} via {@code createObjectInputStream} and
 * calls {@code doReadRemoteInvocationResult} to actually read the object.
 * <p>Can be overridden for custom serialization of the invocation.
 * @param is the InputStream to read from
 * @param codebaseUrl the codebase URL to load classes from if not found locally
 * @return the RemoteInvocationResult object
 * @throws IOException if thrown by I/O methods
 * @throws ClassNotFoundException if thrown during deserialization
 * @see #decorateInputStream
 * @see #createObjectInputStream
 * @see #doReadRemoteInvocationResult
 */
protected RemoteInvocationResult readRemoteInvocationResult(InputStream is, String codebaseUrl)
		throws IOException, ClassNotFoundException {

	ObjectInputStream ois = createObjectInputStream(decorateInputStream(is), codebaseUrl);
	try {
		return doReadRemoteInvocationResult(ois);
	}
	finally {
		ois.close();
	}
}
 
Example 19
Source File: ExoMessage.java    From exo-demo with MIT License 3 votes vote down vote up
/**
 * Deserialize this file transaction from a sequence of bytes
 *
 * @param b
 *            the sequence of bytes
 * @return the file transaction
 * @throws IOException
 *             if anything goes wrong
 * @throws ClassNotFoundException 
 */
public static ExoMessage deserialize(byte[] b) throws IOException, ClassNotFoundException {
	ObjectInputStream o = new ObjectInputStream(new ByteArrayInputStream(b));
	ExoMessage result = (ExoMessage) o.readObject();
	o.close();
	
	return result;
}
 
Example 20
Source File: TestLambdaSerialization.java    From openjdk-systemtest with Apache License 2.0 3 votes vote down vote up
static Object readObject(byte[] baos)  throws IOException, ClassNotFoundException {
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos));

    Object o = in.readObject();
    
    in.close();

    return o;
}