Skip to content

Instantly share code, notes, and snippets.

@yukihane
Created December 21, 2015 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukihane/b14133de6f40d8fb8750 to your computer and use it in GitHub Desktop.
Save yukihane/b14133de6f40d8fb8750 to your computer and use it in GitHub Desktop.
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