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

The following examples show how to use java.io.ObjectInputStream#close() . These examples are extracted from open source projects. 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 Project: mars-sim   File: StarRater.java    License: 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 2
Source Project: netbeans   File: TopComponentTest.java    License: 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 3
/**
    * 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 4
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 5
Source Project: tlaplus   File: ObjectPoolStack.java    License: 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 6
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 7
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 8
@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 9
Source Project: fnlp   File: KNN.java    License: 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 10
Source Project: fnlp   File: Linear.java    License: 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 11
Source Project: yykEmoji   File: RecentEmojiManager.java    License: 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 12
Source Project: Cubert   File: SerializerUtils.java    License: 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 13
Source Project: WheelPicker   File: WheelAreaPicker.java    License: 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 14
Source Project: Robust   File: JavaUtils.java    License: 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 15
Source Project: JANNLab   File: Serializer.java    License: 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 16
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 17
Source Project: TelegramChat   File: Main.java    License: 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
static Object readObject(byte[] baos)  throws IOException, ClassNotFoundException {
    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos));

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

    return o;
}
 
Example 19
Source Project: exo-demo   File: ExoMessage.java    License: 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
/**
 * 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();
	}
}