Here you can find the source of addFileToJar(File fileOrDirectoryToAdd, File extractedJarPath, JarOutputStream target)
public static void addFileToJar(File fileOrDirectoryToAdd, File extractedJarPath, JarOutputStream target) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; public class Main { public static void addFileToJar(File fileOrDirectoryToAdd, File extractedJarPath, JarOutputStream target) throws IOException { String relPath = ""; if (!fileOrDirectoryToAdd.getAbsolutePath().equals(extractedJarPath.getAbsolutePath())) { String fileToAddCanonicalPath = fileOrDirectoryToAdd.getCanonicalPath(); int relStart = extractedJarPath.getCanonicalPath().length() + 1; int relEnd = fileOrDirectoryToAdd.getCanonicalPath().length(); String d = fileToAddCanonicalPath.substring(relStart, relEnd); relPath = d.replace("\\", "/"); }/*from w w w .j a va2 s .c o m*/ BufferedInputStream in = null; try { if (fileOrDirectoryToAdd.isDirectory()) { if (!relPath.isEmpty()) { if (!relPath.endsWith("/")) { relPath += "/"; } JarEntry entry = new JarEntry(relPath); entry.setTime(fileOrDirectoryToAdd.lastModified()); target.putNextEntry(entry); target.closeEntry(); } for (File nestedFile : fileOrDirectoryToAdd.listFiles()) { addFileToJar(nestedFile, extractedJarPath, target); } return; } JarEntry entry = new JarEntry(relPath); entry.setTime(fileOrDirectoryToAdd.lastModified()); target.putNextEntry(entry); in = new BufferedInputStream(new FileInputStream(fileOrDirectoryToAdd)); byte[] buffer = new byte[1024]; while (true) { int count = in.read(buffer); if (count == -1) { break; } target.write(buffer, 0, count); } target.closeEntry(); } finally { if (in != null) { in.close(); } } } }