Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active January 27, 2020 09:55
Show Gist options
  • Select an option

  • Save julianjupiter/c1ffed3ba786beb121b020e730119c10 to your computer and use it in GitHub Desktop.

Select an option

Save julianjupiter/c1ffed3ba786beb121b020e730119c10 to your computer and use it in GitHub Desktop.
Java code to create JAR
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.logging.Logger;
public class JarCreator {
private static final Logger LOGGER = Logger.getLogger(JarCreator.class.getName());
public static void main(String[] args) {
createJar("D:/files/source", "D:/files/dest", "myjar");
}
public static boolean createJar(String source, String destination, String filename) {
final String extension = ".jar";
final String fileName = filename + extension;
final String absolutePath = Paths.get(destination).resolve(fileName).toFile().getAbsolutePath();
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(absolutePath))) {
File sourceDir = new File(source);
if (sourceDir.isDirectory()) {
int length = 0;
byte[] buffer = new byte[1024];
for (File sourceFile : sourceDir.listFiles()) {
JarEntry entry = new JarEntry(sourceFile.getName());
entry.setTime(sourceFile.lastModified());
jos.putNextEntry(entry);
InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
while ((length = is.read(buffer, 0, buffer.length)) != -1) {
jos.write(buffer, 0, length);
}
is.close();
}
}
return true;
} catch (IOException exception) {
LOGGER.severe(() -> "Failed to create JAR");
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment