java.util.zip.ZipEntry Java Examples

The following examples show how to use java.util.zip.ZipEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SARLRuntime.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies if the given JAR file contains a SRE bootstrap.
 *
 * <p>The SRE bootstrap detection is based on the service definition within META-INF folder.
 *
 * @param jarFile the JAR file to test.
 * @return <code>true</code> if the given directory contains a SRE. Otherwise <code>false</code>.
 * @since 0.7
 * @see #containsUnpackedBootstrap(File)
 */
public static boolean containsPackedBootstrap(File jarFile) {
	try (JarFile jFile = new JarFile(jarFile)) {
		final ZipEntry jEntry = jFile.getEntry(SREManifestPreferenceConstants.SERVICE_SRE_BOOTSTRAP);
		if (jEntry != null) {
			try (InputStream is = jFile.getInputStream(jEntry)) {
				try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
					String line = reader.readLine();
					if (line != null) {
						line = line.trim();
						if (!line.isEmpty()) {
							return true;
						}
					}
				}
			}
		}
	} catch (IOException exception) {
		//
	}
	return false;
}
 
Example #2
Source File: ZipTests.java    From nd4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testZip() throws Exception {

    File testFile = File.createTempFile("adasda","Dsdasdea");

    INDArray arr = Nd4j.create(new double[]{1,2,3,4,5,6,7,8,9,0});

    final FileOutputStream fileOut = new FileOutputStream(testFile);
    final ZipOutputStream zipOut = new ZipOutputStream(fileOut);
    zipOut.putNextEntry(new ZipEntry("params"));
    Nd4j.write(zipOut, arr);
    zipOut.flush();
    zipOut.close();


    final FileInputStream fileIn = new FileInputStream(testFile);
    final ZipInputStream zipIn = new ZipInputStream(fileIn);
    ZipEntry entry = zipIn.getNextEntry();
    INDArray read = Nd4j.read(zipIn);
    zipIn.close();


    assertEquals(arr, read);
}
 
Example #3
Source File: ZipUtils.java    From AndroidUtilCode with Apache License 2.0 6 votes vote down vote up
/**
 * Return the files' path in ZIP file.
 *
 * @param zipFile The ZIP file.
 * @return the files' path in ZIP file
 * @throws IOException if an I/O error has occurred
 */
public static List<String> getFilesPath(final File zipFile)
        throws IOException {
    if (zipFile == null) return null;
    List<String> paths = new ArrayList<>();
    ZipFile zip = new ZipFile(zipFile);
    Enumeration<?> entries = zip.entries();
    while (entries.hasMoreElements()) {
        String entryName = ((ZipEntry) entries.nextElement()).getName().replace("\\", "/");
        if (entryName.contains("../")) {
            Log.e("ZipUtils", "entryName: " + entryName + " is dangerous!");
            paths.add(entryName);
        } else {
            paths.add(entryName);
        }
    }
    zip.close();
    return paths;
}
 
Example #4
Source File: UpdateableZipFile.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
public ZipEntry getEntry(String name) {
    if (!file.exists()) {
        return null;
    }
    try {
        InputStream in = FileUtils.openInputStream(file);
        ZipInputStream zin = new ZipInputStream(in);
        try {
            ZipEntry entry = zin.getNextEntry();
            while (entry != null) {
                if (entry.getName().equals(name)) {
                    zin.closeEntry();
                    break;
                }
                entry = zin.getNextEntry();
            }
            return entry;
        } finally {
            IOUtils.closeQuietly(zin);
            IOUtils.closeQuietly(in);
        }
    } catch (IOException e) {
        log.error("Error while retrieving zip entry {}: {}", name, e.toString());
        return null;
    }
}
 
Example #5
Source File: ExtensionUtilsTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
/**
 * Create a generic zip that is a valid extension archive. 
 * 
 * @param zipName name of the zip to create
 * @return a zip file
 * @throws IOException if there's an error creating the zip
 */
private File createExtensionZip(String zipName) throws IOException {

	File f = new File(gLayout.getExtensionArchiveDir().getFile(false), zipName + ".zip");
	try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) {
		out.putNextEntry(new ZipEntry(zipName + "/"));
		out.putNextEntry(new ZipEntry(zipName + "/extension.properties"));

		StringBuilder sb = new StringBuilder();
		sb.append("name:" + zipName);
		byte[] data = sb.toString().getBytes();
		out.write(data, 0, data.length);
		out.closeEntry();
	}

	return f;
}
 
Example #6
Source File: Dex.java    From atlas with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new dex buffer from the dex file {@code file}.
 */
public Dex(File file) throws IOException{
    if (FileUtils.hasArchiveSuffix(file.getName())) {
        ZipFile zipFile = new ZipFile(file);
        ZipEntry entry = zipFile.getEntry(DexFormat.DEX_IN_JAR_NAME);
        if (entry != null) {
            loadFrom(zipFile.getInputStream(entry));
            zipFile.close();
        } else {
            throw new DexException2("Expected " + DexFormat.DEX_IN_JAR_NAME + " in " + file);
        }
    } else if (file.getName().endsWith(".dex")) {
        loadFrom(new FileInputStream(file));
    } else {
        throw new DexException2("unknown output extension: " + file);
    }
}
 
Example #7
Source File: Cartridge.java    From coffee-gb with MIT License 6 votes vote down vote up
private static int[] loadFile(File file) throws IOException {
    String ext = FilenameUtils.getExtension(file.getName());
    try (InputStream is = new FileInputStream(file)) {
        if ("zip".equalsIgnoreCase(ext)) {
            try (ZipInputStream zis = new ZipInputStream(is)) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    String name = entry.getName();
                    String entryExt = FilenameUtils.getExtension(name);
                    if (Stream.of("gb", "gbc", "rom").anyMatch(e -> e.equalsIgnoreCase(entryExt))) {
                        return load(zis, (int) entry.getSize());
                    }
                    zis.closeEntry();
                }
            }
            throw new IllegalArgumentException("Can't find ROM file inside the zip.");
        } else {
            return load(is, (int) file.length());
        }
    }
}
 
Example #8
Source File: PackagedProgramTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtractContainedLibraries() throws Exception {
	String s = "testExtractContainedLibraries";
	byte[] nestedJarContent = s.getBytes(ConfigConstants.DEFAULT_CHARSET);
	File fakeJar = temporaryFolder.newFile("test.jar");
	try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fakeJar))) {
		ZipEntry entry = new ZipEntry("lib/internalTest.jar");
		zos.putNextEntry(entry);
		zos.write(nestedJarContent);
		zos.closeEntry();
	}

	final List<File> files = PackagedProgram.extractContainedLibraries(fakeJar.toURI().toURL());
	Assert.assertEquals(1, files.size());
	Assert.assertArrayEquals(nestedJarContent, Files.readAllBytes(files.iterator().next().toPath()));
}
 
Example #9
Source File: Mojo.java    From capsule-maven-plugin with MIT License 6 votes vote down vote up
String addDirectoryToJar(final JarOutputStream jar, final String outputDirectory) throws IOException {

		// format the output directory
		String formattedOutputDirectory = "";
		if (outputDirectory != null && !outputDirectory.isEmpty()) {
			if (!outputDirectory.endsWith("/")) {
				formattedOutputDirectory = outputDirectory + File.separatorChar;
			} else {
				formattedOutputDirectory = outputDirectory;
			}
		}

		if (!formattedOutputDirectory.isEmpty()) {
			try {
				jar.putNextEntry(new ZipEntry(formattedOutputDirectory));
				jar.closeEntry();
			} catch (final ZipException ignore) {} // ignore duplicate entries and other errors
		}
		return formattedOutputDirectory;
	}
 
Example #10
Source File: ZipFileCreator.java    From microprofile-starter with Apache License 2.0 6 votes vote down vote up
public byte[] createArchive() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ZipOutputStream zos = new ZipOutputStream(baos)) {

        for (Map.Entry<String, byte[]> entry : archiveContent.entrySet()) {

            ZipEntry zipEntry = new ZipEntry(entry.getKey());

            zos.putNextEntry(zipEntry);
            zos.write(entry.getValue());
            zos.closeEntry();

        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    archiveContent.clear();
    return baos.toByteArray();
}
 
Example #11
Source File: DocumentExecutionResource.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void addToZipFile(String filePath, String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {

		File file = new File(filePath + "/" + fileName);
		FileInputStream fis = new FileInputStream(file);
		ZipEntry zipEntry = new ZipEntry(fileName);
		zos.putNextEntry(zipEntry);

		byte[] bytes = new byte[1024];
		int length;
		while ((length = fis.read(bytes)) >= 0) {
			zos.write(bytes, 0, length);
		}

		zos.closeEntry();
		fis.close();
	}
 
Example #12
Source File: B7050028.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example #13
Source File: ZipOutputStreamTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void writingTheSameFileMoreThanOnceWhenInOverwriteModeWritesItOnceToTheZip()
    throws IOException {
  final String name = "example.txt";
  byte[] input1 = "cheese".getBytes(UTF_8);
  byte[] input2 = "cake".getBytes(UTF_8);
  byte[] input3 = "dessert".getBytes(UTF_8);
  try (CustomZipOutputStream out =
      ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING)) {
    ZipEntry entry = new ZipEntry(name);
    out.putNextEntry(entry);
    out.write(input1);
    out.putNextEntry(entry);
    out.write(input2);
    out.putNextEntry(entry);
    out.write(input3);
  }

  assertEquals(ImmutableList.of(new NameAndContent(name, input3)), getExtractedEntries(output));
}
 
Example #14
Source File: JarProcessor.java    From shrinker with Apache License 2.0 6 votes vote down vote up
private List<Pair<String, byte[]>> readZipEntries(Path src) throws IOException {
    ImmutableList.Builder<Pair<String, byte[]>> list = ImmutableList.builder();
    try (ZipInputStream zip = new ZipInputStream(new ByteArrayInputStream(Files.readAllBytes(src)))) {
        for (ZipEntry entry = zip.getNextEntry();
             entry != null;
             entry = zip.getNextEntry()) {
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                // skip
                continue;
            }
            long entrySize = entry.getSize();
            if (entrySize >= Integer.MAX_VALUE) {
                throw new OutOfMemoryError("Too large class file " + name + ", size is " + entrySize);
            }
            byte[] bytes = readByteArray(zip, (int) entrySize);
            list.add(Pair.of(name, bytes));
        }
    }
    return list.build();
}
 
Example #15
Source File: BundleTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void require_that_component_jar_file_contains_compile_artifacts() {
    String depJrt = "dependencies/jrt";
    Pattern jrtPattern = Pattern.compile(depJrt + snapshotOrVersionOrNone);
    ZipEntry jrtEntry = null;

    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        var e = entries.nextElement();
        if (e.getName().startsWith(depJrt)) {
            if (jrtPattern.matcher(e.getName()).matches()) {
                jrtEntry = e;
                break;
            }
        }
    }
    assertNotNull("Component jar file did not contain jrt dependency.", jrtEntry);
}
 
Example #16
Source File: DefinitelyDerefedParamsDriver.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * Write model jar file with nullability model at DEFAULT_ASTUBX_LOCATION
 *
 * @param outPath Path of output model jar file.
 */
private void writeModelJAR(String outPath) throws IOException {
  Preconditions.checkArgument(
      outPath.endsWith(ASTUBX_JAR_SUFFIX), "invalid model file path! " + outPath);
  ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outPath));
  if (!nonnullParams.isEmpty()) {
    ZipEntry entry = new ZipEntry(DEFAULT_ASTUBX_LOCATION);
    // Set the modification/creation time to 0 to ensure that this jars always have the same
    // checksum
    entry.setTime(0);
    entry.setCreationTime(FileTime.fromMillis(0));
    zos.putNextEntry(entry);
    writeModel(new DataOutputStream(zos));
    zos.closeEntry();
  }
  zos.close();
  LOG(VERBOSE, "Info", "wrote model to: " + outPath);
}
 
Example #17
Source File: AndroidResourceOutputs.java    From bazel with Apache License 2.0 6 votes vote down vote up
protected void addEntry(
    String rawName, byte[] content, int storageMethod, @Nullable String comment)
    throws IOException {
  // Fix the path for windows.
  String relativeName = rawName.replace('\\', '/');
  // Make sure the zip entry is not absolute.
  Preconditions.checkArgument(
      !relativeName.startsWith("/"), "Cannot add absolute resources %s", relativeName);
  ZipEntry entry = new ZipEntry(relativeName);
  entry.setMethod(storageMethod);
  entry.setTime(normalizeTime(relativeName));
  entry.setSize(content.length);
  CRC32 crc32 = new CRC32();
  crc32.update(content);
  entry.setCrc(crc32.getValue());
  if (!Strings.isNullOrEmpty(comment)) {
    entry.setComment(comment);
  }

  zip.putNextEntry(entry);
  zip.write(content);
  zip.closeEntry();
}
 
Example #18
Source File: ApkUtils.java    From LibScout with Apache License 2.0 6 votes vote down vote up
public static Set<ZipEntry> getClassesDex(File apkFile) throws ZipException, IOException {
	HashSet<ZipEntry> result = new HashSet<ZipEntry>();
	ZipFile f = new ZipFile(apkFile);
	
    final Enumeration<? extends ZipEntry> entries = f.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        if (entry.getName().matches("classes[1-9]{0,1}\\.dex"))
        	result.add(entry);
    }
    
    // TODO: unzip those entries to tmp dir and return set<Files>

    f.close();
    return result;
}
 
Example #19
Source File: WorkerLoad.java    From arx with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the input from the file.
 *
 * @param config
 * @param zip
 * @throws IOException
 */
private void readInput(final ModelConfiguration config, final ZipFile zip) throws IOException {

    final ZipEntry entry = zip.getEntry("data/input.csv"); //$NON-NLS-1$
    if (entry == null) { return; }
    
    // Read input
    // Use project delimiter for backwards compatibility
    config.setInput(Data.create(new BufferedInputStream(zip.getInputStream(entry)),
                                getCharset(),
                                model.getCSVSyntax().getDelimiter(), getLength(zip, entry)));

    // And encode
    config.getInput().getHandle();
    
    // Disable visualization
    if (model.getMaximalSizeForComplexOperations() > 0 &&
        config.getInput().getHandle().getNumRows() > model.getMaximalSizeForComplexOperations()) {
        model.setVisualizationEnabled(false);
    }
}
 
Example #20
Source File: ZipUtils.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 通过流打包下载文件
 *
 * @param out
 * @param fileName
 * @param
 */
public static void zipFilesByInputStream(ZipOutputStream out, String fileName, InputStream is) throws Exception {
    byte[] buf = new byte[1024];
    try {
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = is.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        is.close();
    } catch (Exception e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
 
Example #21
Source File: TestExtraTime.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
static void testTimeConversions(long from, long to, long step) {
    ZipEntry ze = new ZipEntry("TestExtraTime.java");
    for (long time = from; time <= to; time += step) {
        ze.setTime(time);
        FileTime lastModifiedTime = ze.getLastModifiedTime();
        if (lastModifiedTime.toMillis() != time) {
            throw new RuntimeException("setTime should make getLastModifiedTime " +
                    "return the specified instant: " + time +
                    " got: " + lastModifiedTime.toMillis());
        }
        if (ze.getTime() != time) {
            throw new RuntimeException("getTime after setTime, expected: " +
                    time + " got: " + ze.getTime());
        }
    }
}
 
Example #22
Source File: TestDirectoryStructureUtil.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
private static void addToArchive(ZipOutputStream zos, File dir, File root) throws IOException {
    byte[] buffer = new byte[1024];
    int length;
    int index = root.getAbsolutePath().length();
    for (File file : dir.listFiles()) {
        String name = file.getAbsolutePath().substring(index);
        if (file.isDirectory()) {
            if (file.listFiles().length != 0) {
                addToArchive(zos, file, root);
            } else {
                zos.putNextEntry(new ZipEntry(name + File.separator));
                zos.closeEntry();
            }
        } else {
            try (FileInputStream fis = new FileInputStream(file)) {
                zos.putNextEntry(new ZipEntry(name));
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
            }
        }
    }
}
 
Example #23
Source File: JarResource.java    From nd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns requested ClassPathResource as InputStream object
 *
 * @return File requested at constructor call
 * @throws FileNotFoundException
 */
public InputStream getInputStream() throws FileNotFoundException {
    URL url = this.getUrl();
    if (isJarURL(url)) {
        try {
            url = extractActualUrl(url);
            ZipFile zipFile = new ZipFile(url.getFile());
            ZipEntry entry = zipFile.getEntry(this.resourceName);

            InputStream stream = zipFile.getInputStream(entry);
            return stream;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        File srcFile = this.getFile();
        return new FileInputStream(srcFile);
    }
}
 
Example #24
Source File: ZipDirectory.java    From JavaExercises with GNU General Public License v2.0 5 votes vote down vote up
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
    if (fileToZip.isHidden()) {
        return;
    }
    if (fileToZip.isDirectory()) {
        if (fileName.endsWith("/")) {
            zipOut.putNextEntry(new ZipEntry(fileName));
            zipOut.closeEntry();
        } else {
            zipOut.putNextEntry(new ZipEntry(fileName + "/"));
            zipOut.closeEntry();
        }
        File[] children = fileToZip.listFiles();
        for (File childFile : children) {
            zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
        }
        return;
    }
    FileInputStream fis = new FileInputStream(fileToZip);
    ZipEntry zipEntry = new ZipEntry(fileName);
    zipOut.putNextEntry(zipEntry);
    byte[] bytes = new byte[1024];
    int length;
    while ((length = fis.read(bytes)) >= 0) {
        zipOut.write(bytes, 0, length);
    }
    fis.close();
}
 
Example #25
Source File: ZipFileAccess.java    From BlueMap with MIT License 5 votes vote down vote up
@Override
public InputStream readFile(String path) throws FileNotFoundException, IOException {
	ZipEntry entry = file.getEntry(path);
	if (entry == null) throw new FileNotFoundException("File " + path + " does not exist in this zip-file!");
	
	return file.getInputStream(entry);
}
 
Example #26
Source File: FileUtil.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
/**
 * get a file from a zip file and put it in a specified one
 * 
 * @param zipFile
 *        where to get the file
 * @param entry
 *        the location of the file in the zipFile
 * @param outputFile
 *        where to put the file
 * @return a file in temp directory
 */
public static File getFileFromZip(File zipFile, String entry, File outputFile) {
    try (final FileInputStream fis = new FileInputStream(zipFile);
            final ZipInputStream zin = new ZipInputStream(fis);) {
        ZipEntry zipEntry = zin.getNextEntry();
        while (zipEntry != null && !entry.equals(zipEntry.getName())) {
            zipEntry = zin.getNextEntry();
        }
        if (zipEntry == null) {
            zin.close();
            throw new FileNotFoundException("can't find entry " + entry + " in " + zipFile.getName()); //$NON-NLS-1$ //$NON-NLS-2$
        }

        final byte[] buf = new byte[1024];
        outputFile.delete();
        outputFile.createNewFile();
        int len;
        try (final FileOutputStream out = new FileOutputStream(outputFile);) {
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        return outputFile;
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
    return null;
}
 
Example #27
Source File: JarHelper.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
public static void jarWalk(ZipInputStream input, JarWalkCallback callback) throws IOException {
    ZipEntry e = input.getNextEntry();
    while (e != null) {
        String filename = e.getName();
        if (filename.endsWith(".class")) {
            String classFull = filename.replaceAll("/", ".").substring(0,
                    filename.length() - ".class".length());
            String clazz = classFull.substring(classFull.lastIndexOf('.') + 1);
            callback.process(input, e, classFull, clazz);
        }
        e = input.getNextEntry();
    }
}
 
Example #28
Source File: PatchworkUI.java    From patchwork-patcher with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static InputStream loadOrDownloadMCPConfig(String version, File parent) throws IOException {
	parent.mkdirs();
	File file = new File(parent, "voldemap-" + version + ".tsrg");

	if (!file.exists()) {
		LOGGER.info("Downloading MCPConfig for " + version + ".");
		InputStream stream = new URL("http://files.minecraftforge.net/maven/de/oceanlabs/mcp/mcp_config/" + version + "/mcp_config-" + version + ".zip").openStream();
		ZipInputStream zipInputStream = new ZipInputStream(stream);

		while (true) {
			ZipEntry nextEntry = zipInputStream.getNextEntry();

			if (nextEntry == null) {
				break;
			}

			if (!nextEntry.isDirectory() && nextEntry.getName().endsWith("/joined.tsrg")) {
				FileWriter writer = new FileWriter(file, false);
				IOUtils.copy(zipInputStream, writer, Charset.defaultCharset());
				writer.close();
				LOGGER.info("Downloaded MCPConfig for " + version + ".");
				break;
			}
		}
	} else {
		LOGGER.info("MCPConfig for " + version + " already exists, using downloaded data.");
	}

	return new FileInputStream(file);
}
 
Example #29
Source File: TestUtils.java    From bundletool with Apache License 2.0 5 votes vote down vote up
/** Extracts paths of all files having the given path prefix. */
public static ImmutableList<String> filesUnderPath(ZipFile zipFile, ZipPath pathPrefix) {
  return zipFile.stream()
      .map(ZipEntry::getName)
      .filter(entryName -> ZipPath.create(entryName).startsWith(pathPrefix))
      .collect(toImmutableList());
}
 
Example #30
Source File: DataInstaller.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates the files in the archive, as filtered by previous user actions.
 * 
 * @param dataSet the data set (campaign) to be installed.
 * @param destDir the destination data directory
 * @param files the list of file names
 * 
 * @return true, if all files created ok
 */
private static boolean createFiles(File dataSet, File destDir, Iterable<String> files)
{
	String corrFilename = "";
	try (ZipFile in = new ZipFile(dataSet))
	{
		for (String filename : files)
		{
			ZipEntry entry = in.getEntry(filename);
			corrFilename = correctFileName(destDir, filename);
			if (Logging.isDebugMode())
			{
				Logging.debugPrint("Extracting file: " + filename + " to " + corrFilename);
			}
			copyInputStream(in.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(corrFilename)));
		}
		return true;
	}
	catch (IOException e)
	{
		// Report the error
		Logging.errorPrint("Failed to read data set " + dataSet + " or write file " + corrFilename + " due to ", e);
		ShowMessageDelegate.showMessageDialog(LanguageBundle.getFormattedString("in_diWriteFail", corrFilename),
			TITLE, MessageType.ERROR);
		return false;
	}
}