java.util.jar.JarOutputStream#close ( )源码实例Demo

下面列出了java.util.jar.JarOutputStream#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

static void redefineFoo() throws Exception {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    Attributes mainAttrs = manifest.getMainAttributes();
    mainAttrs.putValue("Agent-Class", FooAgent.class.getName());
    mainAttrs.putValue("Can-Redefine-Classes", "true");
    mainAttrs.putValue("Can-Retransform-Classes", "true");

    Path jar = Files.createTempFile("myagent", ".jar");
    try {
        JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
        add(jarStream, FooAgent.class);
        add(jarStream, FooTransformer.class);
        jarStream.close();
        runAgent(jar);
    } finally {
        Files.deleteIfExists(jar);
    }
}
 
源代码2 项目: BigDataArchitect   文件: EJob.java
/**
 * 创建临时文件*.jar
 * 
 * @param root
 * @return
 * @throws IOException
 */
public static File createTempJar(String root) throws IOException {
    if (!new File(root).exists()) {
        return null;
    }

    final File jarFile = File.createTempFile("EJob-", ".jar", new File(System
            .getProperty("java.io.tmpdir")));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            jarFile.delete();
        }
    });

    JarOutputStream out = new JarOutputStream(new FileOutputStream(jarFile));
    createTempJarInner(out, new File(root), "");
    out.flush();
    out.close();
    return jarFile;
}
 
源代码3 项目: hadoop   文件: TestRunJar.java
private File makeClassLoaderTestJar(String... clsNames) throws IOException {
  File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_2_NAME);
  JarOutputStream jstream =
      new JarOutputStream(new FileOutputStream(jarFile));
  for (String clsName: clsNames) {
    String name = clsName.replace('.', '/') + ".class";
    InputStream entryInputStream = this.getClass().getResourceAsStream(
        "/" + name);
    ZipEntry entry = new ZipEntry(name);
    jstream.putNextEntry(entry);
    BufferedInputStream bufInputStream = new BufferedInputStream(
        entryInputStream, 2048);
    int count;
    byte[] data = new byte[2048];
    while ((count = bufInputStream.read(data, 0, 2048)) != -1) {
      jstream.write(data, 0, count);
    }
    jstream.closeEntry();
  }
  jstream.close();

  return jarFile;
}
 
源代码4 项目: hadoop   文件: TestMRCJCRunJar.java
private File makeTestJar() throws IOException {
  File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME);
  JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jarFile));
  InputStream entryInputStream = this.getClass().getResourceAsStream(
      CLASS_NAME);
  ZipEntry entry = new ZipEntry("org/apache/hadoop/util/" + CLASS_NAME);
  jstream.putNextEntry(entry);
  BufferedInputStream bufInputStream = new BufferedInputStream(
      entryInputStream, 2048);
  int count;
  byte[] data = new byte[2048];
  while ((count = bufInputStream.read(data, 0, 2048)) != -1) {
    jstream.write(data, 0, count);
  }
  jstream.closeEntry();
  jstream.close();

  return jarFile;
}
 
源代码5 项目: big-c   文件: TestFSDownload.java
static LocalResource createJar(FileContext files, Path p,
    LocalResourceVisibility vis) throws IOException {
  LOG.info("Create jar file " + p);
  File jarFile = new File((files.makeQualified(p)).toUri());
  FileOutputStream stream = new FileOutputStream(jarFile);
  LOG.info("Create jar out stream ");
  JarOutputStream out = new JarOutputStream(stream, new Manifest());
  LOG.info("Done writing jar stream ");
  out.close();
  LocalResource ret = recordFactory.newRecordInstance(LocalResource.class);
  ret.setResource(ConverterUtils.getYarnUrlFromPath(p));
  FileStatus status = files.getFileStatus(p);
  ret.setSize(status.getLen());
  ret.setTimestamp(status.getModificationTime());
  ret.setType(LocalResourceType.PATTERN);
  ret.setVisibility(vis);
  ret.setPattern("classes/.*");
  return ret;
}
 
源代码6 项目: netbeans   文件: TestUtil.java
/**
 * Create a fresh JAR file.
 * @param jar the file to create
 * @param contents keys are JAR entry paths, values are text contents (will be written in UTF-8)
 * @param manifest a manifest to store (or null for none)
 * @deprecated use {@link JarBuilder} instead
 */
@Deprecated
public static void createJar(File jar, Map<String,String> contents, Manifest manifest) throws IOException {
    if (manifest != null) {
        manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); // workaround for JDK bug
    }
    jar.getParentFile().mkdirs();
    OutputStream os = new FileOutputStream(jar);
    try {
        JarOutputStream jos = manifest != null ? new JarOutputStream(os, manifest) : new JarOutputStream(os);
        for (Map.Entry<String,String> entry : contents.entrySet()) {
            String path = entry.getKey();
            byte[] data = entry.getValue().getBytes("UTF-8");
            JarEntry je = new JarEntry(path);
            je.setSize(data.length);
            CRC32 crc = new CRC32();
            crc.update(data);
            je.setCrc(crc.getValue());
            jos.putNextEntry(je);
            jos.write(data);
        }
        jos.close();
    } finally {
        os.close();
    }
}
 
源代码7 项目: hbase   文件: ClassLoaderTestHelper.java
/**
 * Add a list of jar files to another jar file under a specific folder.
 * It is used to generated coprocessor jar files which can be loaded by
 * the coprocessor class loader.  It is for testing usage only so we
 * don't be so careful about stream closing in case any exception.
 *
 * @param targetJar the target jar file
 * @param libPrefix the folder where to put inner jar files
 * @param srcJars the source inner jar files to be added
 * @throws Exception if anything doesn't work as expected
 */
public static void addJarFilesToJar(File targetJar,
    String libPrefix, File... srcJars) throws Exception {
  FileOutputStream stream = new FileOutputStream(targetJar);
  JarOutputStream out = new JarOutputStream(stream, new Manifest());
  byte[] buffer = new byte[BUFFER_SIZE];

  for (File jarFile: srcJars) {
    // Add archive entry
    JarEntry jarAdd = new JarEntry(libPrefix + jarFile.getName());
    jarAdd.setTime(jarFile.lastModified());
    out.putNextEntry(jarAdd);

    // Write file to archive
    FileInputStream in = new FileInputStream(jarFile);
    while (true) {
      int nRead = in.read(buffer, 0, buffer.length);
      if (nRead <= 0) {
        break;
      }

      out.write(buffer, 0, nRead);
    }
    in.close();
  }
  out.close();
  stream.close();
  LOG.info("Adding jar file to outer jar file completed");
}
 
源代码8 项目: rogue-jndi   文件: HttpServer.java
/**
 * Create an executable jar based on supplied bytecode
 */
byte[] createJar(byte[] exportByteCode, String className) throws Exception {

	ByteArrayOutputStream bout = new ByteArrayOutputStream();
	JarOutputStream jarOut = new JarOutputStream(bout);
	jarOut.putNextEntry(new ZipEntry(className + ".class"));
	jarOut.write(exportByteCode);
	jarOut.closeEntry();
	jarOut.close();
	bout.close();

	return bout.toByteArray();
}
 
源代码9 项目: big-c   文件: TestRunJar.java
/**
 * Construct a jar with two files in it in our
 * test dir.
 */
private void makeTestJar() throws IOException {
  File jarFile = new File(TEST_ROOT_DIR, TEST_JAR_NAME);
  JarOutputStream jstream =
      new JarOutputStream(new FileOutputStream(jarFile));
  jstream.putNextEntry(new ZipEntry("foobar.txt"));
  jstream.closeEntry();
  jstream.putNextEntry(new ZipEntry("foobaz.txt"));
  jstream.closeEntry();
  jstream.close();
}
 
源代码10 项目: stratosphere   文件: ServerTestUtils.java
/**
 * Creates a jar file from the class with the given class name and stores it in the directory for temporary files.
 * 
 * @param className
 *        the name of the class to create a jar file from
 * @return a {@link File} object referring to the jar file
 * @throws IOException
 *         thrown if an error occurs while writing the jar file
 */
public static File createJarFile(String className) throws IOException {

	final String jarPath = getTempDir() + File.separator + className + ".jar";
	final File jarFile = new File(jarPath);

	if (jarFile.exists()) {
		jarFile.delete();
	}

	final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarPath), new Manifest());
	final String classPath = JobManagerITCase.class.getResource("").getPath() + className + ".class";
	final File classFile = new File(classPath);

	String packageName = JobManagerITCase.class.getPackage().getName();
	packageName = packageName.replaceAll("\\.", "\\/");
	jos.putNextEntry(new JarEntry("/" + packageName + "/" + className + ".class"));

	final FileInputStream fis = new FileInputStream(classFile);
	final byte[] buffer = new byte[1024];
	int num = fis.read(buffer);

	while (num != -1) {
		jos.write(buffer, 0, num);
		num = fis.read(buffer);
	}

	fis.close();
	jos.close();

	return jarFile;
}
 
private File createJar(File folder, String name, String resources[]) throws Exception {
    folder.mkdirs();
    File f = new File(folder,name);
    if (!f.exists()) {
        f.createNewFile();
    }
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(f));
    for (int i = 0; i < resources.length; i++) {
        jos.putNextEntry(new ZipEntry(resources[i]));
    }
    jos.close();
    return f;
}
 
源代码12 项目: api-compiler   文件: ToolUtil.java
/**
 * Writes a set of files with directory structure to a .jar. The content is a map from file path
 * to one of {@link Doc}, {@link String}, or {@code byte[]}.
 */
public static void writeJar(Map<String, ?> content, String outputName) throws IOException {
  OutputStream outputStream = new FileOutputStream(outputName);
  JarOutputStream jarFile = new JarOutputStream(outputStream);
  OutputStreamWriter writer = new OutputStreamWriter(jarFile, StandardCharsets.UTF_8);
  try {
    for (Map.Entry<String, ?> entry : content.entrySet()) {
      jarFile.putNextEntry(new JarEntry(entry.getKey()));
      Object value = entry.getValue();
      if (value instanceof Doc) {
        writer.write(((Doc) value).prettyPrint());
        writer.flush();
      } else if (value instanceof String) {
        writer.write((String) value);
        writer.flush();
      } else if (value instanceof byte[]) {
        jarFile.write((byte[]) value);
      } else {
        throw new IllegalArgumentException("Expected one of Doc, String, or byte[]");
      }
      jarFile.closeEntry();
    }
  } finally {
    writer.close();
    jarFile.close();
  }
}
 
源代码13 项目: steam   文件: Util.java
/**
   * Create jar archive out of files list. Names in archive have paths starting from relativeToDir
   *
   * @param tobeJared     list of files
   * @param relativeToDir starting directory for paths
   * @return jar as byte array
   * @throws IOException
   */
  public static byte[] createJarArchiveByteArray(File[] tobeJared, String relativeToDir) throws IOException {
    int BUFFER_SIZE = 10240;
    byte buffer[] = new byte[BUFFER_SIZE];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    JarOutputStream out = new JarOutputStream(stream, new Manifest());

    for (File t : tobeJared) {
      if (t == null || !t.exists() || t.isDirectory()) {
        if (t != null && !t.isDirectory())
          logger.error("Can't add to jar {}", t);
        continue;
      }
      // Create jar entry
      String filename = t.getPath().replace(relativeToDir, "").replace("\\", "/");
//      if (filename.endsWith("MANIFEST.MF")) { // skip to avoid duplicates
//        continue;
//      }
      JarEntry jarAdd = new JarEntry(filename);
      jarAdd.setTime(t.lastModified());
      out.putNextEntry(jarAdd);

      // Write file to archive
      FileInputStream in = new FileInputStream(t);
      while (true) {
        int nRead = in.read(buffer, 0, buffer.length);
        if (nRead <= 0)
          break;
        out.write(buffer, 0, nRead);
      }
      in.close();
    }

    out.close();
    stream.close();
    return stream.toByteArray();
  }
 
源代码14 项目: samoa   文件: Utils.java
public static void buildModulesPackage(List<String> modulesNames) {
	System.out.println(System.getProperty("user.dir"));
	try {
		String baseDir = System.getProperty("user.dir");
		List<File> filesArray = new ArrayList<>();
		for (String module : modulesNames) {
			module = "/"+module.replace(".", "/")+".class";
			filesArray.add(new File(baseDir+module));
		}
		String output = System.getProperty("user.home") + "/modules.jar";

		Manifest manifest = new Manifest();
		manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
				"1.0");
		manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_URL,
				"http://samoa.yahoo.com");
		manifest.getMainAttributes().put(
				Attributes.Name.IMPLEMENTATION_VERSION, "0.1");
		manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VENDOR,
				"Yahoo");
		manifest.getMainAttributes().put(
				Attributes.Name.IMPLEMENTATION_VENDOR_ID, "SAMOA");

		BufferedOutputStream bo;

		bo = new BufferedOutputStream(new FileOutputStream(output));
		JarOutputStream jo = new JarOutputStream(bo, manifest);

		File[] files = filesArray.toArray(new File[filesArray.size()]);
		addEntries(jo,files, baseDir, "");

		jo.close();
		bo.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

}
 
源代码15 项目: onos   文件: CfgDefGenerator.java
public void generate() throws IOException {
    JarOutputStream jar = new JarOutputStream(new FileOutputStream(resourceJar));
    for (JavaClass javaClass : builder.getClasses()) {
        processClass(jar, javaClass);
    }
    jar.close();
}
 
源代码16 项目: netbeans   文件: PrepareData.java
private static void prepareJarFilesystem( File root, String name, int count, String prefix ) throws IOException {
    File jar = new File( root, name );
    FileOutputStream stream = new FileOutputStream( jar );
    JarOutputStream jarStream = new JarOutputStream( stream );
    for( int i=0; i<count; i++ ) {
        jarStream.putNextEntry( new ZipEntry( prefix + i ) );
        jarStream.closeEntry();
    }
    jarStream.close();
}
 
源代码17 项目: DataLoader   文件: ModifyUtils.java
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;
}
 
源代码18 项目: jdk8u-dev-jdk   文件: LargeJarEntry.java
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();
        }
    }
 
源代码19 项目: dragonwell8_jdk   文件: LargeJarEntry.java
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();
        }
    }
 
源代码20 项目: jdk8u60   文件: WsimportTool.java
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();
            }
        }
    }
}