下面列出了java.util.jar.JarOutputStream#putNextEntry ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void setUp() throws Exception {
clearWorkDir();
f = new File(getWorkDir(), "m.jar");
Manifest man = new Manifest();
Attributes attr = man.getMainAttributes();
attr.putValue("OpenIDE-Module", "m.test");
attr.putValue("OpenIDE-Module-Public-Packages", "-");
attr.putValue("Manifest-Version", "1.0");
JarOutputStream os = new JarOutputStream(new FileOutputStream(f), man);
os.putNextEntry(new JarEntry("META-INF/namedservices/ui/javax.swing.JComponent"));
os.write("javax.swing.JButton\n".getBytes("UTF-8"));
os.closeEntry();
os.close();
FileObject fo = FileUtil.createData(FileUtil.getConfigRoot(), "ui/ch/my/javax-swing-JPanel.instance");
}
private File changeManifest(File orig, String manifest) throws IOException {
File f = new File(getWorkDir(), orig.getName());
Manifest mf = new Manifest(new ByteArrayInputStream(manifest.getBytes("utf-8")));
mf.getMainAttributes().putValue("Manifest-Version", "1.0");
JarOutputStream os = new JarOutputStream(new FileOutputStream(f), mf);
JarFile jf = new JarFile(orig);
Enumeration<JarEntry> en = jf.entries();
InputStream is;
while (en.hasMoreElements()) {
JarEntry e = en.nextElement();
if (e.getName().equals("META-INF/MANIFEST.MF")) {
continue;
}
os.putNextEntry(e);
is = jf.getInputStream(e);
FileUtil.copy(is, os);
is.close();
os.closeEntry();
}
os.close();
return f;
}
protected void addJarFile(String jarFileName, String... sources) throws IOException {
File jarFile = getTempFile(jarFileName);
jarFile.getParentFile().mkdirs();
options.fileUtil().appendSourcePath(jarFile.getPath());
JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile));
try {
for (int i = 0; i < sources.length; i += 2) {
String name = sources[i];
String source = sources[i + 1];
JarEntry fooEntry = new JarEntry(name);
jar.putNextEntry(fooEntry);
jar.write(source.getBytes(Charset.defaultCharset()));
jar.closeEntry();
}
} finally {
jar.close();
}
}
/**
* Merges two jars. The first jar will get merged into the output jar.
* A running set of jar entries is kept so that duplicates are skipped.
* This has the side-effect that the first instance of a given entry will be added
* and all subsequent entries are skipped.
*
* @param jin The input jar
* @param jout The output jar
* @param entries The set of existing entries. Note that this set will be mutated as part of this call.
* @return The set of entries.
* @throws IOException
*/
private Set<String> copy(JarInputStream jin, JarOutputStream jout, Set<String> entries) throws IOException {
byte[] buffer = new byte[1024];
for(JarEntry entry = jin.getNextJarEntry(); entry != null; entry = jin.getNextJarEntry()) {
if(entries.contains(entry.getName())) {
continue;
}
LOG.debug("Merging jar entry {}", entry.getName());
entries.add(entry.getName());
jout.putNextEntry(entry);
int len = 0;
while( (len = jin.read(buffer)) > 0 ) {
jout.write(buffer, 0, len);
}
}
return entries;
}
/**
* Adds a compiled class file to the target jar stream.
*
* @param fromClass The class to be added
* @param target The target jar stream
*/
private static void addFile(Class fromClass, JarOutputStream target) throws IOException {
String classEntry = fromClass.getName().replace('.', '/') + ".class";
URL classURL = fromClass.getClassLoader().getResource(classEntry);
if (classURL != null) {
JarEntry entry = new JarEntry(classEntry);
target.putNextEntry(entry);
if (!classURL.toString().contains("!")) {
String fileName = classURL.getFile();
writeBytes(fileName, target);
} else {
try (InputStream stream = fromClass.getClassLoader().getResourceAsStream(classEntry)) {
writeBytes(stream, target);
}
}
target.closeEntry();
}
}
private void saveJar(JarFile jar) {
File dest = new File(System.getProperty("user.home") + "/07kit/gamepack.jar");
logger.info("Caching " + jar.getName() + " to " + dest.getAbsolutePath());
try {
JarOutputStream out = new JarOutputStream(new FileOutputStream(dest));
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
out.putNextEntry(entry);
InputStream in = jar.getInputStream(entry);
while (in.available() > 0) {
out.write(in.read());
}
out.closeEntry();
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
static void copyJarFile(JarFile in, JarOutputStream out) throws IOException {
byte[] buffer = new byte[1 << 14];
for (JarEntry je : Collections.list(in.entries())) {
out.putNextEntry(je);
InputStream ein = in.getInputStream(je);
for (int nr; 0 < (nr = ein.read(buffer)); ) {
out.write(buffer, 0, nr);
}
}
in.close();
markJarFile(out); // add PACK200 comment
}
private void writeDependencies(JarOutputStream zOs)
throws IOException
{
Configuration targetConfig;
targetConfig = _project.getConfigurations().getByName("runtime");
for (File lib : targetConfig.resolve()) {
if (isBootJar(lib)) {
copyBootJar(zOs, lib);
}
String name = lib.getName();
zOs.setLevel(0);
ZipEntry entry = new ZipEntry("lib/" + name);
entry.setMethod(ZipEntry.STORED);
entry.setSize(lib.length());
entry.setCrc(calculateCrc(lib.toPath()));
zOs.putNextEntry(entry);
Files.copy(lib.toPath(), zOs);
}
}
protected static void addFile(File zFile, JarOutputStream zOut) throws IOException {
//Check..
if (!zFile.exists() || !zFile.canRead()) {
return;
}
if (mVerbose) {
System.out.println("Adding file : " + zFile.getPath());
}
//Add it..
if (zFile.isDirectory()) {
//Cycle through
File[] files = zFile.listFiles();
for (File ff : files) {
addFile(ff, zOut);
}
} else {
// Add archive entry
JarEntry jarAdd = new JarEntry(zFile.getName());
jarAdd.setTime(zFile.lastModified());
zOut.putNextEntry(jarAdd);
// Write file to archive
FileInputStream in = new FileInputStream(zFile);
while (true) {
int nRead = in.read(mBuffer, 0, mBuffer.length);
if (nRead <= 0)
break;
zOut.write(mBuffer, 0, nRead);
}
in.close();
}
}
/** Combines the JARs into one. If both JARs have the same entry, the entry from the first JAR is used. */
static public void mergeJars (String firstJar, String secondJar, String outJar) throws IOException {
if (DEBUG) debug("scar", "Merging JARs: " + firstJar + " + " + secondJar + " -> " + outJar);
JarFile firstJarFile = new JarFile(firstJar);
JarFile secondJarFile = new JarFile(secondJar);
HashSet<String> names = new HashSet();
for (Enumeration<JarEntry> entries = firstJarFile.entries(); entries.hasMoreElements();)
names.add(entries.nextElement().getName().replace('\\', '/'));
for (Enumeration<JarEntry> entries = secondJarFile.entries(); entries.hasMoreElements();)
names.add(entries.nextElement().getName().replace('\\', '/'));
mkdir(parent(outJar));
JarOutputStream outJarStream = new JarOutputStream(new FileOutputStream(outJar));
outJarStream.setLevel(Deflater.BEST_COMPRESSION);
for (String name : names) {
InputStream input;
ZipEntry entry = firstJarFile.getEntry(name);
if (entry != null)
input = firstJarFile.getInputStream(entry);
else {
entry = firstJarFile.getEntry(name.replace('/', '\\'));
if (entry != null)
input = firstJarFile.getInputStream(entry);
else {
entry = secondJarFile.getEntry(name);
input = secondJarFile.getInputStream(entry != null ? entry : secondJarFile.getEntry(name.replace('/', '\\')));
}
}
outJarStream.putNextEntry(new JarEntry(name));
copyStream(input, outJarStream);
outJarStream.closeEntry();
}
firstJarFile.close();
secondJarFile.close();
outJarStream.close();
}
private static void writeJarredFile(JarOutputStream jos, String file, String suffix, byte[] bytes) {
String fileName = file.replace(".", "/") + "." + suffix;
JarEntry ze = new JarEntry(fileName);
try {
ze.setSize(bytes.length);
jos.putNextEntry(ze);
jos.write(bytes);
jos.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static void createJAR(File cluster, String moduleName, Class metaInfHandler)
throws IOException {
File xml = new File(new File(new File(cluster, "config"), "Modules"), moduleName + ".xml");
File jar = new File(new File(cluster, "modules"), moduleName + ".jar");
xml.getParentFile().mkdirs();
jar.getParentFile().mkdirs();
Manifest mf = new Manifest();
mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
mf.getMainAttributes().putValue("OpenIDE-Module", moduleName.replace('-', '.'));
mf.getMainAttributes().putValue("OpenIDE-Module-Public-Packages", "-");
JarOutputStream os = new JarOutputStream(new FileOutputStream(jar), mf);
os.putNextEntry(new JarEntry("META-INF/services/org.netbeans.CLIHandler"));
os.write(metaInfHandler.getName().getBytes());
os.close();
FileWriter w = new FileWriter(xml);
w.write(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE module PUBLIC \"-//NetBeans//DTD Module Status 1.0//EN\"\n" +
" \"http://www.netbeans.org/dtds/module-status-1_0.dtd\">\n" +
"<module name=\"" + moduleName.replace('-', '.') + "\">\n" +
" <param name=\"autoload\">false</param>\n" +
" <param name=\"eager\">false</param>\n" +
" <param name=\"enabled\">true</param>\n" +
" <param name=\"jar\">modules/" + moduleName + ".jar</param>\n" +
" <param name=\"release\">2</param>\n" +
" <param name=\"reloadable\">false</param>\n" +
" <param name=\"specversion\">3.4.0.1</param>\n" +
"</module>\n");
w.close();
}
public static void writeEntry(@Nonnull File jarFile, @Nonnull String name, @Nonnull String content) throws IOException {
JarOutputStream stream = new JarOutputStream(new FileOutputStream(jarFile));
try {
stream.putNextEntry(new JarEntry(name));
stream.write(content.getBytes("UTF-8"));
stream.closeEntry();
}
finally {
stream.close();
}
}
private static void writeJarredFile(JarOutputStream jos, String file, String suffix, byte[] bytes) {
String fileName = file.replace(".", "/") + "." + suffix;
JarEntry ze = new JarEntry(fileName);
try {
ze.setSize(bytes.length);
jos.putNextEntry(ze);
jos.write(bytes);
jos.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void addFileToJar(JarOutputStream jar, File source, String entryName) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) {
JarEntry entry = new JarEntry(entryName);
entry.setTime(source.lastModified());
jar.putNextEntry(entry);
copyStream(in, jar);
jar.closeEntry();
}
}
public static void packFile(JarOutputStream out, JarEntry oldEntry, String path, byte[] data) throws IOException {
JarEntry newEntry = new JarEntry(path);
newEntry.setTime(oldEntry.getTime());
// newEntry.setMethod(oldEntry.getMethod());
newEntry.setComment(oldEntry.getComment());
newEntry.setExtra(oldEntry.getExtra());
out.putNextEntry(newEntry);
out.write(data, 0, data.length);
out.closeEntry();
}
private void jarArtifacts(WsimportListener listener) throws IOException {
File zipFile = new File(options.clientjar);
if(!zipFile.isAbsolute()) {
zipFile = new File(options.destDir, options.clientjar);
}
FileOutputStream fos;
if (!options.quiet) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVING_ARTIFACTS(zipFile));
}
BufferedInputStream bis = null;
FileInputStream fi = null;
fos = new FileOutputStream(zipFile);
JarOutputStream jos = new JarOutputStream(fos);
try {
String base = options.destDir.getCanonicalPath();
for(File f: options.getGeneratedFiles()) {
//exclude packaging the java files in the jar
if(f.getName().endsWith(".java")) {
continue;
}
if(options.verbose) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVE_ARTIFACT(f, options.clientjar));
}
String entry = f.getCanonicalPath().substring(base.length()+1).replace(File.separatorChar, '/');
fi = new FileInputStream(f);
bis = new BufferedInputStream(fi);
JarEntry jarEntry = new JarEntry(entry);
jos.putNextEntry(jarEntry);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = bis.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
}
} finally {
try {
if (bis != null) {
bis.close();
}
} finally {
if (jos != null) {
jos.close();
}
if (fi != null) {
fi.close();
}
}
}
}
public static File modifyJar(File file, File tempDir) throws IOException {
JarFile jarFile = new JarFile(file);
System.out.println(TAG + "tempDir: " + tempDir.getAbsolutePath());
File outputFile = new File(tempDir, file.getName());
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(outputFile));
Enumeration enumeration = jarFile.entries();
while (enumeration.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) enumeration.nextElement();
InputStream inputStream = jarFile.getInputStream(jarEntry);
String entryName = jarEntry.getName();
ZipEntry zipEntry = new ZipEntry(entryName);
jarOutputStream.putNextEntry(zipEntry);
byte[] modifiedClassBytes = null;
byte[] sourceClassBytes = IOUtils.toByteArray(inputStream);
if (TARGET_CLASS.equals(jarEntry.getName())) {
ClassReader cr = new ClassReader(sourceClassBytes);
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cr.accept(cw, 0);
{
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "test", "()V", null, null);
mv.visitCode();
Label l0 = new Label();
mv.visitLabel(l0);
mv.visitLineNumber(18, l0);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
cw.visitEnd();
modifiedClassBytes = cw.toByteArray();
}
if (modifiedClassBytes == null) {
jarOutputStream.write(sourceClassBytes);
} else {
jarOutputStream.write(modifiedClassBytes);
}
jarOutputStream.closeEntry();
}
jarOutputStream.close();
jarFile.close();
return outputFile;
}
private void jarArtifacts(WsimportListener listener) throws IOException {
File zipFile = new File(options.clientjar);
if(!zipFile.isAbsolute()) {
zipFile = new File(options.destDir, options.clientjar);
}
FileOutputStream fos;
if (!options.quiet) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVING_ARTIFACTS(zipFile));
}
BufferedInputStream bis = null;
FileInputStream fi = null;
fos = new FileOutputStream(zipFile);
JarOutputStream jos = new JarOutputStream(fos);
try {
String base = options.destDir.getCanonicalPath();
for(File f: options.getGeneratedFiles()) {
//exclude packaging the java files in the jar
if(f.getName().endsWith(".java")) {
continue;
}
if(options.verbose) {
listener.message(WscompileMessages.WSIMPORT_ARCHIVE_ARTIFACT(f, options.clientjar));
}
String entry = f.getCanonicalPath().substring(base.length()+1).replace(File.separatorChar, '/');
fi = new FileInputStream(f);
bis = new BufferedInputStream(fi);
JarEntry jarEntry = new JarEntry(entry);
jos.putNextEntry(jarEntry);
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = bis.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
}
} finally {
try {
if (bis != null) {
bis.close();
}
} finally {
if (jos != null) {
jos.close();
}
if (fi != null) {
fi.close();
}
}
}
}
public static void main(String[] args) throws Exception {
String srcDir = System.getProperty("test.src", ".");
String keystore = srcDir + "/JarSigning.keystore";
String jarName = "largeJarEntry.jar";
// Set java.io.tmpdir to the current working dir (see 6474350)
System.setProperty("java.io.tmpdir", System.getProperty("user.dir"));
// first, create jar file with 8M uncompressed entry
// note, we set the max heap size to 8M in @run tag above
byte[] bytes = new byte[1000000];
CRC32 crc = new CRC32();
for (int i=0; i<8; i++) {
crc.update(bytes);
}
JarEntry je = new JarEntry("large");
je.setSize(8000000l);
je.setMethod(JarEntry.STORED);
je.setCrc(crc.getValue());
File file = new File(jarName);
FileOutputStream os = new FileOutputStream(file);
JarOutputStream jos = new JarOutputStream(os);
jos.setMethod(JarEntry.STORED);
jos.putNextEntry(je);
for (int i=0; i<8; i++) {
jos.write(bytes, 0, bytes.length);
}
jos.close();
String[] jsArgs = { "-keystore", keystore, "-storepass", "bbbbbb",
jarName, "b" };
// now, try to sign it
try {
sun.security.tools.jarsigner.Main.main(jsArgs);
} catch (OutOfMemoryError err) {
throw new Exception("Test failed with OutOfMemoryError", err);
} finally {
// remove jar file
file.delete();
}
}