Skip to content

Instantly share code, notes, and snippets.

@yukihane yukihane/Main.java
Created Dec 21, 2015

Embed
What would you like to do?
package com.github.yukihane.jar;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Main main = new Main();
Asset target = new Asset(new Resource1("my resource"), new Resource2(2016));
File jar = new File("asset.jar");
main.compress(jar, target);
Asset result = main.decompress(jar);
System.out.println("res1: " + result.res1.name + ", res2: " + result.res2.year);
}
void compress(File jar, Asset target) throws IOException {
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) {
JarEntry ze = new JarEntry("asset");
jos.putNextEntry(ze);
try (ObjectOutputStream os = new ObjectOutputStream(jos)) {
os.writeObject(target);
}
}
}
Asset decompress(File jar) throws IOException, ClassNotFoundException {
try (JarInputStream jis = new JarInputStream(new FileInputStream(jar))) {
jis.getNextJarEntry();
try (ObjectInputStream is = new ObjectInputStream(jis)) {
return (Asset) is.readObject();
}
}
}
}
class Asset implements Serializable {
Resource1 res1;
Resource2 res2;
public Asset(Resource1 res1, Resource2 res2) {
this.res1 = res1;
this.res2 = res2;
}
}
class Resource1 implements Serializable {
String name;
Resource1(String name) {
this.name = name;
}
}
class Resource2 implements Serializable {
int year;
Resource2(int length) {
this.year = length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.