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

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

源代码1 项目: 07kit   文件: AppletLoader.java
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();
    }
}
 
源代码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 项目: 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;
}
 
源代码4 项目: helidon-build-tools   文件: Jar.java
private void addIndex(JarOutputStream jar) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final IndexWriter writer = new IndexWriter(out);
    try {
        writer.write(index);
        final ByteArrayInputStream data = new ByteArrayInputStream(out.toByteArray());
        final JarEntry entry = new JarEntry(JANDEX_INDEX_RESOURCE_PATH);
        entry.setLastModifiedTime(FileTime.fromMillis(System.currentTimeMillis()));
        jar.putNextEntry(entry);
        StreamUtils.transfer(data, jar);
        jar.flush();
        jar.closeEntry();
    } catch (IOException e) {
        Log.warn("Unable to add index: %s", e);
    }
}
 
源代码5 项目: scheduling   文件: JarUtils.java
/**
 * Create a jar file that contains all the directory listed in directories parameter.
 * @param directoriesAndFiles the list of directories and files to be jarred.
 * @param manifestVerion the version of the jar manifest (can be null).
 * @param mainClass the main class of the jar (can be null).
 * @param jarInternalClasspath the class-path of the jar (can be null).
 * @param crc the CRC32 of all jar entries. Can be null if no crc is needed.
 * @throws IOException if the jar file cannot be created.
 * @return the jar file as a byte[].
 */
public static byte[] jarDirectoriesAndFiles(String[] directoriesAndFiles, String manifestVerion, String mainClass,
        String jarInternalClasspath, CRC32 crc) throws IOException {

    // Fill in a byte array
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Create jar stream
    JarOutputStream jos = new JarOutputStream(baos,
                                              JarUtils.createManifest(manifestVerion,
                                                                      mainClass,
                                                                      jarInternalClasspath));
    jos.setLevel(COMP_LEVEL);

    // Jar file is ready
    jarIt(jos, directoriesAndFiles, crc);

    // Close the file output streams
    jos.flush();
    jos.close();
    baos.flush();
    baos.close();
    return baos.toByteArray();

}
 
源代码6 项目: brooklyn-server   文件: CatalogResourceTest.java
private static File createJar(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "jar");

    JarOutputStream zip = new JarOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        JarEntry ze = new JarEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}
 
源代码7 项目: netbeans   文件: FreeformProjectGeneratorTest.java
public void createRealJarFile(File f) throws Exception {
        OutputStream os = new FileOutputStream(f);
        try {
            JarOutputStream jos = new JarOutputStream(os);
//            jos.setMethod(ZipEntry.STORED);
            JarEntry entry = new JarEntry("foo.txt");
//            entry.setSize(0L);
//            entry.setTime(System.currentTimeMillis());
//            entry.setCrc(new CRC32().getValue());
            jos.putNextEntry(entry);
            jos.flush();
            jos.close();
        } finally {
            os.close();
        }
    }
 
源代码8 项目: o2oa   文件: JarTools.java
private static void write(File file, String parentPath, JarOutputStream jos) {
	if (file.exists()) {
		if (file.isDirectory()) {
			parentPath += file.getName() + File.separator;
			for (File f : file.listFiles()) {
				write(f, parentPath, jos);
			}
		} else {
			try (FileInputStream fis = new FileInputStream(file)) {
				String name = parentPath + file.getName();
				/* 必须,否则打出来的包无法部署在Tomcat上 */
				name = StringUtils.replace(name, "\\", "/");
				JarEntry entry = new JarEntry(name);
				entry.setMethod(JarEntry.DEFLATED);
				jos.putNextEntry(entry);
				byte[] content = new byte[2048];
				int len;
				while ((len = fis.read(content)) != -1) {
					jos.write(content, 0, len);
					jos.flush();
				}
				jos.closeEntry();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
 
源代码9 项目: Knowage-Server   文件: Zipper.java
/**
 * This method compress all the content of targetDir into jar file outFile. If outFile alredy exist it will be overwritten.
 * 
 * @throws IOException
 * @params targetDir the folder that must be compressed into a jar
 * @params outFile the output jar file generated compressing targetDir content
 */
public void compressToJar(File targetDir, File outFile) throws IOException {

	logger.trace("IN");

	// try {
	Assert.assertNotNull("Input parametr [targetDir] cannot be null", targetDir);
	Assert.assertTrue("Input parametr [targetDir] must be a valid folder", targetDir.exists() && targetDir.isDirectory());
	Assert.assertNotNull("Input parametr [outFile] cannot be null", outFile);

	if (!outFile.getParentFile().exists()) {
		logger.warn("Output folder [{}] does not exist. It will be created", outFile.getParentFile().getAbsolutePath());
		outFile.getParentFile().mkdir();
	}

	if (outFile.exists()) {
		logger.warn("A mapping jar file named [{}] alredy exists. It will be overwritten", outFile.getAbsoluteFile());
		outFile.delete();
	}

	FileOutputStream fileOutputStream = new FileOutputStream(outFile);
	JarOutputStream zipOutputStream = new JarOutputStream(fileOutputStream);
	// zipOutputStream.setMethod(ZipOutputStream.STORED);

	compressFolder(targetDir, targetDir, zipOutputStream);

	zipOutputStream.flush();
	zipOutputStream.close();

	logger.info("Mapping jar created succesfully: [{}]", true);

	// } catch(Exception e) {
	// throw new RuntimeException("An error occurred while compressing folder [" + targetDir +"] into jar file [" + outFile + "]", e);
	// } finally {
	// logger.trace("OUT");
	// }

}
 
源代码10 项目: netbeans   文件: URLMapperTest.java
/**
 * Check that jar: URLs are correctly mapped back into JarFileSystem resources.
 * @see "#39190"
 */
public void testJarMapping() throws Exception {
    clearWorkDir();
    File workdir = getWorkDir();
    File jar = new File(workdir, "test.jar");
    String textPath = "x.txt";
    OutputStream os = new FileOutputStream(jar);
    try {
        JarOutputStream jos = new JarOutputStream(os);
        jos.setMethod(ZipEntry.STORED);
        JarEntry entry = new JarEntry(textPath);
        entry.setSize(0L);
        entry.setTime(System.currentTimeMillis());
        entry.setCrc(new CRC32().getValue());
        jos.putNextEntry(entry);
        jos.flush();
        jos.close();
    } finally {
        os.close();
    }
    assertTrue("JAR was created", jar.isFile());
    assertTrue("JAR is not empty", jar.length() > 0L);
    JarFileSystem jfs = new JarFileSystem();
    jfs.setJarFile(jar);
    Repository.getDefault().addFileSystem(jfs);
    FileObject rootFO = jfs.getRoot();
    FileObject textFO = jfs.findResource(textPath);
    assertNotNull("JAR contains a/b.txt", textFO);
    String rootS = "jar:" + BaseUtilities.toURI(jar) + "!/";
    URL rootU = new URL(rootS);
    URL textU = new URL(rootS + textPath);
    assertEquals("correct FO -> URL for root", rootU, URLMapper.findURL(rootFO, URLMapper.EXTERNAL));
    assertEquals("correct FO -> URL for " + textPath, textU, URLMapper.findURL(textFO, URLMapper.EXTERNAL));
    assertTrue("correct URL -> FO for root", Arrays.asList(URLMapper.findFileObjects(rootU)).contains(rootFO));
    assertTrue("correct URL -> FO for " + textPath, Arrays.asList(URLMapper.findFileObjects(textU)).contains(textFO));
}
 
源代码11 项目: Box   文件: Main.java
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                     outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    context.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return false;
    }

    return true;
}
 
源代码12 项目: buck   文件: Main.java
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    context.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                ex.getMessage());
        }
        return false;
    }

    return true;
}
 
源代码13 项目: flink   文件: JarHelper.java
/**
 * Recursively jars up the given path under the given directory.
 */
private void jarDir(File dirOrFile2jar, JarOutputStream jos, String path)
	throws IOException {
	if (mVerbose) {
		System.out.println("checking " + dirOrFile2jar);
	}
	if (dirOrFile2jar.isDirectory()) {
		String[] dirList = dirOrFile2jar.list();
		String subPath = (path == null) ? "" : (path + dirOrFile2jar.getName() + SEP);
		if (path != null) {
			JarEntry je = new JarEntry(subPath);
			je.setTime(dirOrFile2jar.lastModified());
			jos.putNextEntry(je);
			jos.flush();
			jos.closeEntry();
		}
		for (int i = 0; i < dirList.length; i++) {
			File f = new File(dirOrFile2jar, dirList[i]);
			jarDir(f, jos, subPath);
		}
	} else if (dirOrFile2jar.exists()) {
		if (dirOrFile2jar.getCanonicalPath().equals(mDestJarName)) {
			if (mVerbose) {
				System.out.println("skipping " + dirOrFile2jar.getPath());
			}
			return;
		}

		if (mVerbose) {
			System.out.println("adding " + dirOrFile2jar.getPath());
		}
		FileInputStream fis = new FileInputStream(dirOrFile2jar);
		try {
			JarEntry entry = new JarEntry(path + dirOrFile2jar.getName());
			entry.setTime(dirOrFile2jar.lastModified());
			jos.putNextEntry(entry);
			while ((mByteCount = fis.read(mBuffer)) != -1) {
				jos.write(mBuffer, 0, mByteCount);
				if (mVerbose) {
					System.out.println("wrote " + mByteCount + " bytes");
				}
			}
			jos.flush();
			jos.closeEntry();
		} catch (IOException ioe) {
			throw ioe;
		} finally {
			fis.close();
		}
	}
}
 
源代码14 项目: Box   文件: Main.java
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                     outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    context.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            context.err.println("\ntrouble writing output:");
            ex.printStackTrace(context.err);
        } else {
            context.err.println("\ntrouble writing output: " +
                               ex.getMessage());
        }
        return false;
    }

    return true;
}
 
源代码15 项目: java-n-IDE-for-Android   文件: Main.java
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private static boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                    outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    DxConsole.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            DxConsole.err.println("\ntrouble writing output:");
            ex.printStackTrace(DxConsole.err);
        } else {
            DxConsole.err.println("\ntrouble writing output: " +
                    ex.getMessage());
        }
        return false;
    }

    return true;
}
 
源代码16 项目: javaide   文件: Extractor.java
private boolean writeExternalAnnotations(@NonNull File annotationsZip) {
    try {
        FileOutputStream fileOutputStream = new FileOutputStream(annotationsZip);
        JarOutputStream zos = new JarOutputStream(fileOutputStream);

        try {
            // TODO: Extract to share with keep rules
            List<String> sortedPackages = new ArrayList<String>(itemMap.keySet());
            Collections.sort(sortedPackages);
            for (String pkg : sortedPackages) {
                // Note: Using / rather than File.separator: jar lib requires it
                String name = pkg.replace('.', '/') + "/annotations.xml";

                JarEntry outEntry = new JarEntry(name);
                zos.putNextEntry(outEntry);

                StringWriter stringWriter = new StringWriter(1000);
                PrintWriter writer = new PrintWriter(stringWriter);
                try {
                    writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                            "<root>");

                    Map<String, List<Item>> classMap = itemMap.get(pkg);
                    List<String> classes = new ArrayList<String>(classMap.keySet());
                    Collections.sort(classes);
                    for (String cls : classes) {
                        List<Item> items = classMap.get(cls);
                        Collections.sort(items);
                        for (Item item : items) {
                            item.write(writer);
                        }
                    }

                    writer.println("</root>\n");
                    writer.close();
                    String xml = stringWriter.toString();

                    // Validate
                    if (assertionsEnabled()) {
                        Document document = checkDocument(pkg, xml, false);
                        if (document == null) {
                            error("Could not parse XML document back in for entry " + name
                                    + ": invalid XML?\n\"\"\"\n" + xml + "\n\"\"\"\n");
                            return false;
                        }
                    }
                    byte[] bytes = xml.getBytes(Charsets.UTF_8);
                    zos.write(bytes);
                    zos.closeEntry();
                } finally {
                    writer.close();
                }
            }
        } finally {
            zos.flush();
            zos.close();
        }
    } catch (IOException ioe) {
        error(ioe.toString());
        return false;
    }

    return true;
}
 
源代码17 项目: NullAway   文件: BytecodeAnnotator.java
/**
 * Annotates the methods and method parameters in the classes in "classes.jar" in the given aar
 * file with the specified annotations.
 *
 * @param inputZip AarFile to annotate.
 * @param zipOS OutputStream of the output aar file.
 * @param nonnullParams Map from methods to their nonnull params.
 * @param nullableReturns List of methods that return nullable.
 * @param debug flag to output debug logs.
 * @throws IOException if an error happens when reading or writing to AAR/JAR/class streams.
 */
public static void annotateBytecodeInAar(
    ZipFile inputZip,
    ZipOutputStream zipOS,
    MethodParamAnnotations nonnullParams,
    MethodReturnAnnotations nullableReturns,
    boolean stripJarSignatures,
    boolean debug)
    throws IOException {
  BytecodeAnnotator.debug = debug;
  LOG(debug, "DEBUG", "nullableReturns: " + nullableReturns);
  LOG(debug, "DEBUG", "nonnullParams: " + nonnullParams);
  // Error Prone doesn't like usages of the old Java Enumerator APIs. ZipFile does not implement
  // Iterable, and likely never will (see  https://bugs.openjdk.java.net/browse/JDK-6581715).
  // Additionally, inputZip.stream() returns a Stream<? extends ZipEntry>, and a for-each loop
  // has trouble handling the corresponding ::iterator  method reference. So this seems like the
  // best remaining way:
  Iterator<? extends ZipEntry> zipIterator = inputZip.stream().iterator();
  while (zipIterator.hasNext()) {
    ZipEntry zipEntry = zipIterator.next();
    InputStream is = inputZip.getInputStream(zipEntry);
    zipOS.putNextEntry(new ZipEntry(zipEntry.getName()));
    if (zipEntry.getName().equals("classes.jar")) {
      JarInputStream jarIS = new JarInputStream(is);
      JarEntry inputJarEntry = jarIS.getNextJarEntry();

      ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
      JarOutputStream jarOS = new JarOutputStream(byteArrayOS);
      while (inputJarEntry != null) {
        copyAndAnnotateJarEntry(
            inputJarEntry,
            jarIS,
            jarOS,
            nonnullParams,
            nullableReturns,
            androidNullableDesc,
            androidNonnullDesc,
            stripJarSignatures);
        inputJarEntry = jarIS.getNextJarEntry();
      }
      jarOS.flush();
      jarOS.close();
      zipOS.write(byteArrayOS.toByteArray());
    } else {
      zipOS.write(IOUtils.toByteArray(is));
    }
    zipOS.closeEntry();
  }
}
 
源代码18 项目: capsule   文件: Jar.java
private static void addEntry(JarOutputStream jarOut, String path, byte[] data) throws IOException {
    jarOut.putNextEntry(new JarEntry(path));
    jarOut.write(data);
    jarOut.flush();
    jarOut.closeEntry();
}
 
源代码19 项目: javaide   文件: Main.java
/**
 * Creates a jar file from the resources (including dex file arrays).
 *
 * @param fileName {@code non-null;} name of the file
 * @return whether the creation was successful
 */
private static boolean createJar(String fileName) {
    /*
     * Make or modify the manifest (as appropriate), put the dex
     * array into the resources map, and then process the entire
     * resources map in a uniform manner.
     */

    try {
        Manifest manifest = makeManifest();
        OutputStream out = openOutput(fileName);
        JarOutputStream jarOut = new JarOutputStream(out, manifest);

        try {
            for (Map.Entry<String, byte[]> e :
                    outputResources.entrySet()) {
                String name = e.getKey();
                byte[] contents = e.getValue();
                JarEntry entry = new JarEntry(name);
                int length = contents.length;

                if (args.verbose) {
                    DxConsole.out.println("writing " + name + "; size " + length + "...");
                }

                entry.setSize(length);
                jarOut.putNextEntry(entry);
                jarOut.write(contents);
                jarOut.closeEntry();
            }
        } finally {
            jarOut.finish();
            jarOut.flush();
            closeOutput(out);
        }
    } catch (Exception ex) {
        if (args.debug) {
            DxConsole.err.println("\ntrouble writing output:");
            ex.printStackTrace(DxConsole.err);
        } else {
            DxConsole.err.println("\ntrouble writing output: " +
                    ex.getMessage());
        }
        return false;
    }

    return true;
}
 
源代码20 项目: unmock-plugin   文件: ProcessRealAndroidJar.java
public static boolean createJarArchive(String outfile, String srcFolder) throws Exception {

        FileOutputStream dest = new FileOutputStream(new File(outfile));

        JarOutputStream out = new JarOutputStream(new BufferedOutputStream(dest));

        addToJar(out, new File(srcFolder), new File(srcFolder));

        out.flush();
        out.close();

        return true;
    }