Java Code Examples for java.util.zip.ZipInputStream#close()

The following examples show how to use java.util.zip.ZipInputStream#close() . 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: ZipArchive.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
public static File unzip(File in, File out) throws FileNotFoundException, IOException {
    byte[] buffer = new byte[1024];
    ZipInputStream zis = new ZipInputStream(new FileInputStream(in));
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        String fileName = ze.getName();
        File newFile = new File(out, fileName);
        if (ze.isDirectory()) {
            newFile.mkdirs();
        } else {
            new File(newFile.getParent()).mkdirs();
            FileOutputStream fos = new FileOutputStream(newFile);
            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
            fos.close();
        }
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.close();
    return out;
}
 
Example 2
Source File: BundleHelper.java    From ShizuruNotes with Apache License 2.0 6 votes vote down vote up
public static List<String> listEntries(InputStream input) throws IOException {
  List<String> result = new ArrayList<String>();
  ZipInputStream zis = new ZipInputStream(input);
  ZipEntry entry;
  try {
    while ((entry = zis.getNextEntry()) != null) {
      if (!entry.isDirectory()) {
        result.add(entry.getName());
      }
      zis.closeEntry();
    }
  } finally {
    zis.close();
  }
  return result;
}
 
Example 3
Source File: LocalResourcesTools.java    From webery with MIT License 6 votes vote down vote up
protected void getClasses(File archive, List<Class> l) {
    try {
        ZipInputStream zip = new ZipInputStream(new FileInputStream(archive));
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            String name = entry.toString();
            if (name.startsWith("WEB-INF/classes/"))
                name = name.substring("WEB-INF/classes/".length());
            Class c = getClass(name);
            if (c != null)
                l.add(c);
        }
        zip.close();
    } catch (IOException ignored) {
    }
}
 
Example 4
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void ZipExplodeTo(InputStream stream, File outfolder) throws FileNotFoundException, IOException  {
	byte buffer[] = new byte[10240];
	outfolder.mkdirs();
	ZipInputStream zis = new ZipInputStream(stream);
	ZipEntry ze = zis.getNextEntry();
	while (ze != null) {
		FileOutputStream fout = new FileOutputStream(outfolder.getAbsolutePath()+File.separator+ze.getName());
		int len;
		while ((len=zis.read(buffer))>0) {
			fout.write(buffer,0,len);
		}
		fout.close();
		ze=zis.getNextEntry();
	}
	zis.closeEntry();
	zis.close();
	stream.close();
}
 
Example 5
Source File: FileHelper.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
/*************ZIP file operation***************/
public static boolean readZipFile(String zipFileName, StringBuffer crc) {
	try {
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
		ZipEntry entry;
		while ((entry = zis.getNextEntry()) != null) {
			long size = entry.getSize();
			crc.append(entry.getCrc() + ", size: " + size);
        }
        zis.close();
	} catch (Exception ex) {
		Log.i(TAG,"Exception: " + ex.toString());
		return false;
	}
	return true;
}
 
Example 6
Source File: Utils.java    From skin-composer with MIT License 6 votes vote down vote up
/**
 * Extracts a zip file specified by the zipFilePath to a directory specified by
 * destDirectory (will be created if does not exists)
 * @param zipFile
 * @param destDirectory
 * @throws IOException
 */
public static void unzip(FileHandle zipFile, FileHandle destDirectory) throws IOException {
    destDirectory.mkdirs();
    
    InputStream is = zipFile.read();
    ZipInputStream zis = new ZipInputStream(is);
    
    ZipEntry entry = zis.getNextEntry();
    // iterates over entries in the zip file
    while (entry != null) {
        if (!entry.isDirectory()) {
            // if the entry is a file, extracts it
            extractFile(zis, destDirectory.child(entry.getName()));
        } else {
            // if the entry is a directory, make the directory
            destDirectory.child(entry.getName()).mkdirs();
        }
        zis.closeEntry();
        entry = zis.getNextEntry();
    }
    is.close();
    zis.close();
}
 
Example 7
Source File: SiteExportServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private List<String> getEntries(ZipInputStream zipStream) throws Exception
{
    ZipEntry entry = null;
    List<String> entries = Lists.newArrayList();
    while ((entry = zipStream.getNextEntry()) != null)
    {
        if (entry.getName().endsWith("acp"))
        {
            entries.addAll(getAcpEntries(zipStream));
        }
        entries.add(entry.getName());
        zipStream.closeEntry();
    }
    zipStream.close();
    return entries;
}
 
Example 8
Source File: SwingUI.java    From halfnes with GNU General Public License v3.0 5 votes vote down vote up
private File extractRomFromZip(String zipName, String romName) throws IOException {
    final ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipName));
    ZipEntry entry;
    do {
        entry = zipStream.getNextEntry();
    } while ((entry != null) && (!entry.getName().equals(romName)));
    if (entry == null) {
        zipStream.close();
        throw new IOException("Cannot find file " + romName + " inside archive " + zipName);
    }
    //name temp. extracted file after parent zip and file inside

    //note: here's the bug, when it saves the temp file if it's in a folder 
    //in the zip it's trying to put it in the same folder outside the zip
    final File outputFile = new File(new File(zipName).getParent()
            + File.separator + FileUtils.stripExtension(new File(zipName).getName())
            + " - " + romName);
    if (outputFile.exists()) {
        this.messageBox("Cannot extract file. File " + outputFile.getCanonicalPath() + " already exists.");
        zipStream.close();
        return null;
    }
    final byte[] buf = new byte[4096];
    final FileOutputStream fos = new FileOutputStream(outputFile);
    int numBytes;
    while ((numBytes = zipStream.read(buf, 0, buf.length)) != -1) {
        fos.write(buf, 0, numBytes);
    }
    zipStream.close();
    fos.close();
    return outputFile;
}
 
Example 9
Source File: Util.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * @source http://stackoverflow.com/a/27050680
 */
public static void unzip(InputStream zipFile, File targetDirectory) throws Exception {
    ZipInputStream in = new ZipInputStream(new BufferedInputStream(zipFile));
    try {
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[8192];
        while ((ze = in.getNextEntry()) != null) {
            File file = new File(targetDirectory, ze.getName());
            File dir = ze.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                throw new Exception("Failed to ensure directory: " + dir.getAbsolutePath());
            }
            if (ze.isDirectory()) {
                continue;
            }
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            try {
                while ((count = in.read(buffer)) != -1)
                    out.write(buffer, 0, count);
            } finally {
                out.close();
            }
            long time = ze.getTime();
            if (time > 0) {
                file.setLastModified(time);
            }
        }
    } finally {
        in.close();
    }
}
 
Example 10
Source File: ZipInputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_available() throws Exception {

        File resources = Support_Resources.createTempFolder();
        Support_Resources.copyFile(resources, null, "hyts_ZipFile.zip");
        File fl = new File(resources, "hyts_ZipFile.zip");
        FileInputStream fis = new FileInputStream(fl);

        ZipInputStream zis1 = new ZipInputStream(fis);
        ZipEntry entry = zis1.getNextEntry();
        assertNotNull("No entry in the archive.", entry);
        long entrySize = entry.getSize();
        assertTrue("Entry size was < 1", entrySize > 0);
        int i = 0;
        while (zis1.available() > 0) {
            zis1.skip(1);
            i++;
        }
        if (i != entrySize) {
            fail("ZipInputStream.available or ZipInputStream.skip does not " +
                    "working properly. Only skipped " + i +
                    " bytes instead of " + entrySize + " for entry " + entry.getName());
        }
        assertEquals(0, zis1.skip(1));
        assertEquals(0, zis1.available());
        zis1.closeEntry();
        assertEquals(1, zis.available());
        zis1.close();
        try {
            zis1.available();
            fail("IOException expected");
        } catch (IOException ee) {
            // expected
        }
    }
 
Example 11
Source File: HJAdb.java    From HJMirror with MIT License 5 votes vote down vote up
private boolean unzip() {
    try {
        // Open zip InputSteam.
        ZipInputStream zip = new ZipInputStream(new FileInputStream(ADB_ZIP));
        // Create Target Folder.
        File outputDirectory = new File("./");
        if (!outputDirectory.exists()) {
            outputDirectory.mkdir();
        }
        int len;
        byte[] buffer = new byte[4096];
        ZipEntry entry;
        while ((entry = zip.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                File file = new File(outputDirectory + File.separator+ entry.getName());
                File folder = file.getParentFile();
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                FileOutputStream fileWriter = new FileOutputStream(file);
                while ((len = zip.read(buffer)) > 0) {
                    fileWriter.write(buffer, 0, len);
                }
                fileWriter.flush();
                fileWriter.close();
                // Make adb file executable.
                if (file.getName().equals("adb")) {
                    file.setExecutable(true);
                }
            }
        }
        zip.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 12
Source File: Zips.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void unzip(final InputStream read, final File destination, final boolean noparent, final FileFilter fileFilter) throws IOException {
    Objects.requireNonNull(fileFilter, "'fileFilter' is required.");

    Files.dir(destination);
    Files.writable(destination);

    try {
        ZipInputStream e = new ZipInputStream(read);

        ZipEntry entry;
        while ((entry = e.getNextEntry()) != null) {
            String path = entry.getName();
            if (noparent) {
                path = path.replaceFirst("^[^/]+/", "");
            }

            File file = new File(destination, path);
            if (!fileFilter.accept(file)) continue;

            if (entry.isDirectory()) {
                Files.mkdir(file);
            } else {
                Files.mkdir(file.getParentFile());
                IO.copy(e, file);
                long lastModified = entry.getTime();
                if (lastModified > 0L) {
                    file.setLastModified(lastModified);
                }
            }
        }

        e.close();
    } catch (IOException var9) {
        throw new IOException("Unable to unzip " + read, var9);
    }
}
 
Example 13
Source File: Loader.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Retrieves a zipped ImagePlus from the given InputStream. The stream is not closed and must be closed elsewhere. No error checking is done as to whether the stream actually contains a zipped tiff file. */
protected ImagePlus unzipTiff(final InputStream i_stream, final String title) {
	ImagePlus imp;
	try {
		// Reading a zipped tiff file in the database


		/* // works but not faster
                      byte[] bytes = null;
                      // new style: RAM only
                      ByteArrayOutputStream out = new ByteArrayOutputStream();
                      byte[] buf = new byte[4096];
                      int len;
                      int length = 0;
                      while (true) {
                              len = i_stream.read(buf);
                              if (len<0) break;
                              length += len;
                              out.write(buf, 0, len);
                      }
                      Inflater infl = new Inflater();
                      infl.setInput(out.toByteArray(), 0, length);
                      int buflen = length + length;
                      buf = new byte[buflen]; //short almost for sure
                      int offset = 0;
                      ArrayList al = new ArrayList();
                      while (true) {
                              len = infl.inflate(buf, offset, buf.length);
                              al.add(buf);
                              if (0 == infl.getRemaining()) break;
                              buf = new byte[length*2];
                              offset += len;
                      }
                      infl.end();
                      byte[][] b = new byte[al.size()][];
                      al.toArray(b);
                      int blength = buflen * (b.length -1) + len; // the last may be shorter
                      bytes = new byte[blength];
                      for (int i=0; i<b.length -1; i++) {
                              System.arraycopy(b[i], 0, bytes, i*buflen, buflen);
                      }
                      System.arraycopy(b[b.length-1], 0, bytes, buflen * (b.length-1), len);
		 */


		//OLD, creates tmp file (archive style)
		final ZipInputStream zis = new ZipInputStream(i_stream);
		final ByteArrayOutputStream out = new ByteArrayOutputStream();
		final byte[] buf = new byte[4096]; //copying savagely from ImageJ's Opener.openZip()
		//ZipEntry entry = zis.getNextEntry(); // I suspect this is needed as an iterator
		int len;
		while (true) {
			len = zis.read(buf);
			if (len<0) break;
			out.write(buf, 0, len);
		}
		zis.close();
		final byte[] bytes = out.toByteArray();

		ij.IJ.redirectErrorMessages();
		imp = opener.openTiff(new ByteArrayInputStream(bytes), title);

		//old
		//ij.IJ.redirectErrorMessages();
		//imp = new Opener().openTiff(i_stream, title);
	} catch (final Exception e) {
		IJError.print(e);
		return null;
	}
	return imp;
}
 
Example 14
Source File: ScriptBean.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Import the script meta-data and source from a zip file.
 */
public boolean importScript(byte[] bytes) {
	try {
		checkLogin();
		
		ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
		ZipInputStream zip = new ZipInputStream(stream);
		
		ZipEntry entry = zip.getNextEntry();
		byte[] icon = null;
		byte[] source = null;
		boolean found = false;
		while (entry != null) {
			byte[] fileBytes = BotBean.loadImageFile(zip, false);
			if (entry.getName().equals("meta.xml")) {
				JAXBContext context = JAXBContext.newInstance(ScriptConfig.class);
				Unmarshaller marshaller = context.createUnmarshaller();
				ByteArrayInputStream fileStream = new ByteArrayInputStream(fileBytes);
				ScriptConfig config = (ScriptConfig)marshaller.unmarshal(fileStream);
				if (!createInstance(config)) {
					return false;
				}
				found = true;
			} else if (entry.getName().equals("icon.jpg")) {
				icon = fileBytes;
			} else if (entry.getName().startsWith("source")) {
				source = fileBytes;
			}
			zip.closeEntry();
			entry = zip.getNextEntry();
		}
		zip.close();
		stream.close();
		
		if (!found) {
			throw new BotException("Missing meta.xml file in export archive");
		}
		if (icon != null) {
			update(icon);
		}
		if (source != null) {
			updateScriptSource(new String(source, "UTF-8"), false, "0.1");
		}
	} catch (Exception exception) {
		error(exception);
		return false;
	}
	return true;
}
 
Example 15
Source File: DistributedCacheUtilImpl.java    From pentaho-hadoop-shims with Apache License 2.0 4 votes vote down vote up
/**
 * Extract a zip archive to a directory.
 *
 * @param archive Zip archive to extract
 * @param dest    Destination directory. This must not exist!
 * @return Directory the zip was extracted into
 * @throws IllegalArgumentException when the archive file does not exist or the destination directory already exists
 * @throws IOException
 * @throws KettleFileException
 */
public FileObject extract( FileObject archive, FileObject dest ) throws IOException, KettleFileException {
  if ( !archive.exists() ) {
    throw new IllegalArgumentException( "archive does not exist: " + archive.getURL().getPath() );
  }

  if ( dest.exists() ) {
    throw new IllegalArgumentException( "destination already exists" );
  }
  dest.createFolder();

  try {
    byte[] buffer = new byte[ DEFAULT_BUFFER_SIZE ];
    int len = 0;
    ZipInputStream zis = new ZipInputStream( archive.getContent().getInputStream() );
    try {
      ZipEntry ze;
      while ( ( ze = zis.getNextEntry() ) != null ) {
        FileObject entry = KettleVFS.getFileObject( dest + Const.FILE_SEPARATOR + ze.getName() );
        FileObject parent = entry.getParent();
        if ( parent != null ) {
          parent.createFolder();
        }
        if ( ze.isDirectory() ) {
          entry.createFolder();
          continue;
        }

        OutputStream os = KettleVFS.getOutputStream( entry, false );
        try {
          while ( ( len = zis.read( buffer ) ) > 0 ) {
            os.write( buffer, 0, len );
          }
        } finally {
          if ( os != null ) {
            os.close();
          }
        }
      }
    } finally {
      if ( zis != null ) {
        zis.close();
      }
    }
  } catch ( Exception ex ) {
    // Try to clean up the temp directory and all files
    if ( !deleteDirectory( dest ) ) {
      throw new KettleFileException( "Could not clean up temp dir after error extracting", ex );
    }
    throw new KettleFileException( "error extracting archive", ex );
  }

  return dest;
}
 
Example 16
Source File: ReadParams.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception{
    /* initialise stuff */
    File fn = new File("x.ReadBounds");
    FileOutputStream fout = new FileOutputStream(fn);
    for (int i = 0; i < 32; i++) {
        fout.write(i);
    }
    fout.close();

    byte b[] = new byte[64];
    for(int i = 0; i < 64; i++) {
        b[i] = 1;
    }

    /* test all input streams */
    FileInputStream fis = new FileInputStream(fn);
    doTest(fis);
    doTest1(fis);
    fis.close();

    BufferedInputStream bis =
        new BufferedInputStream(new MyInputStream(1024));
    doTest(bis);
    doTest1(bis);
    bis.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    doTest(bais);
    doTest1(bais);
    bais.close();

    FileOutputStream fos = new FileOutputStream(fn);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeInt(12345);
    oos.writeObject("Today");
    oos.writeObject(new Integer(32));
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fn));
    doTest(ois);
    doTest1(ois);
    ois.close();

    DataInputStream dis = new DataInputStream(new MyInputStream(1024));
    doTest(dis);
    doTest1(dis);
    dis.close();

    LineNumberInputStream lis =
        new LineNumberInputStream(new MyInputStream(1024));
    doTest(lis);
    doTest1(lis);
    lis.close();

    PipedOutputStream pos = new PipedOutputStream();
    PipedInputStream pis = new PipedInputStream();
    pos.connect(pis);
    pos.write(b, 0, 64);
    doTest(pis);
    doTest1(pis);
    pis.close();

    PushbackInputStream pbis =
        new PushbackInputStream(new MyInputStream(1024));
    doTest(pbis);
    doTest1(pbis);
    pbis.close();

    StringBufferInputStream sbis =
        new StringBufferInputStream(new String(b));
    doTest(sbis);
    doTest1(sbis);
    sbis.close();

    SequenceInputStream sis =
        new SequenceInputStream(new MyInputStream(1024),
                                new MyInputStream(1024));
    doTest(sis);
    doTest1(sis);
    sis.close();

    ZipInputStream zis = new ZipInputStream(new FileInputStream(fn));
    doTest(zis);
    doTest1(zis);
    zis.close();

    byte[] data = new byte[256];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DeflaterOutputStream dos = new DeflaterOutputStream(bos);
    dos.write(data, 0, data.length);
    dos.close();
    InflaterInputStream ifs = new InflaterInputStream
        (new ByteArrayInputStream(bos.toByteArray()));
    doTest(ifs);
    doTest1(ifs);
    ifs.close();

    /* cleanup */
    fn.delete();
}
 
Example 17
Source File: AlipayController.java    From springboot-pay-example with Apache License 2.0 4 votes vote down vote up
/**
 * 下载下来的是一个【账号_日期.csv.zip】文件(zip压缩文件名,里面有多个.csv文件)
 * 账号_日期_业务明细 : 支付宝业务明细查询
 * 账号_日期_业务明细(汇总):支付宝业务汇总查询
 *
 * 注意:如果数据量比较大,该方法可能需要更长的执行时间
 * @param billDownLoadUrl
 * @return
 * @throws IOException
 */
private List<String> downloadBill(String billDownLoadUrl) throws IOException {
    String ordersStr = "";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .setSocketTimeout(60000)
            .build();
    HttpGet httpRequest = new HttpGet(billDownLoadUrl);
    httpRequest.setConfig(config);
    CloseableHttpResponse response = null;
    byte[] data = null;
    try {
        response = httpClient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        data = EntityUtils.toByteArray(entity);
    } finally {
        response.close();
        httpClient.close();
    }
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(data), Charset.forName("GBK"));
    ZipEntry zipEntry = null;
    try{
        while( (zipEntry = zipInputStream.getNextEntry()) != null){
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try{
                String name = zipEntry.getName();
                // 只要明细不要汇总
                if(name.contains("汇总")){
                    continue;
                }
                byte[] byteBuff = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = zipInputStream.read(byteBuff)) != -1) {
                    byteArrayOutputStream.write(byteBuff, 0, bytesRead);
                }
                ordersStr = byteArrayOutputStream.toString("GBK");
            }finally {
                byteArrayOutputStream.close();
                zipInputStream.closeEntry();
            }
        }
    } finally {
        zipInputStream.close();
    }

    if (ordersStr.equals("")) {
        return null;
    }
    String[] bills = ordersStr.split("\r\n");
    List<String> billList = Arrays.asList(bills);
    billList = billList.parallelStream().map(item -> item.replace("\t", "")).collect(Collectors.toList());

    return billList;
}
 
Example 18
Source File: AlbumImpl.java    From screenshot-tests-for-android with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the file in which the screenshot is stored, or null if this is not a valid screenshot
 *
 * <p>TODO: Adjust tests to no longer use this method. It's quite sketchy and inefficient.
 */
@Nullable
File getScreenshotFile(String name) throws IOException {
  if (mZipOutputStream != null) {
    // This needs to be a valid file before we can read from it.
    mZipOutputStream.close();
  }

  File bundle = new File(mDir, SCREENSHOT_BUNDLE_FILE_NAME);
  if (!bundle.isFile()) {
    return null;
  }

  ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(bundle));
  try {
    String filename = getScreenshotFilenameInternal(name);
    byte[] buffer = new byte[BUFFER_SIZE];

    ZipEntry entry;
    while ((entry = zipInputStream.getNextEntry()) != null) {
      if (!filename.equals(entry.getName())) {
        continue;
      }

      File file = File.createTempFile(name, ".png");
      FileOutputStream fileOutputStream = new FileOutputStream(file);
      try {
        int len;
        while ((len = zipInputStream.read(buffer)) > 0) {
          fileOutputStream.write(buffer, 0, len);
        }
      } finally {
        fileOutputStream.close();
      }
      return file;
    }
  } finally {
    zipInputStream.close();
  }
  return null;
}
 
Example 19
Source File: ReadParams.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception{
    /* initialise stuff */
    File fn = new File("x.ReadBounds");
    FileOutputStream fout = new FileOutputStream(fn);
    for (int i = 0; i < 32; i++) {
        fout.write(i);
    }
    fout.close();

    byte b[] = new byte[64];
    for(int i = 0; i < 64; i++) {
        b[i] = 1;
    }

    /* test all input streams */
    FileInputStream fis = new FileInputStream(fn);
    doTest(fis);
    doTest1(fis);
    fis.close();

    BufferedInputStream bis =
        new BufferedInputStream(new MyInputStream(1024));
    doTest(bis);
    doTest1(bis);
    bis.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    doTest(bais);
    doTest1(bais);
    bais.close();

    FileOutputStream fos = new FileOutputStream(fn);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeInt(12345);
    oos.writeObject("Today");
    oos.writeObject(new Integer(32));
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fn));
    doTest(ois);
    doTest1(ois);
    ois.close();

    DataInputStream dis = new DataInputStream(new MyInputStream(1024));
    doTest(dis);
    doTest1(dis);
    dis.close();

    LineNumberInputStream lis =
        new LineNumberInputStream(new MyInputStream(1024));
    doTest(lis);
    doTest1(lis);
    lis.close();

    PipedOutputStream pos = new PipedOutputStream();
    PipedInputStream pis = new PipedInputStream();
    pos.connect(pis);
    pos.write(b, 0, 64);
    doTest(pis);
    doTest1(pis);
    pis.close();

    PushbackInputStream pbis =
        new PushbackInputStream(new MyInputStream(1024));
    doTest(pbis);
    doTest1(pbis);
    pbis.close();

    StringBufferInputStream sbis =
        new StringBufferInputStream(new String(b));
    doTest(sbis);
    doTest1(sbis);
    sbis.close();

    SequenceInputStream sis =
        new SequenceInputStream(new MyInputStream(1024),
                                new MyInputStream(1024));
    doTest(sis);
    doTest1(sis);
    sis.close();

    ZipInputStream zis = new ZipInputStream(new FileInputStream(fn));
    doTest(zis);
    doTest1(zis);
    zis.close();

    byte[] data = new byte[256];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DeflaterOutputStream dos = new DeflaterOutputStream(bos);
    dos.write(data, 0, data.length);
    dos.close();
    InflaterInputStream ifs = new InflaterInputStream
        (new ByteArrayInputStream(bos.toByteArray()));
    doTest(ifs);
    doTest1(ifs);
    ifs.close();

    /* cleanup */
    fn.delete();
}
 
Example 20
Source File: UploadDatasetFileResource.java    From Knowage-Server with GNU Affero General Public License v3.0 3 votes vote down vote up
private FileItem unzipUploadedFile(FileItem uploaded) {

		logger.debug("Method unzipUploadedFile(): Start");

		FileItem tempFileItem = null;

		try {
			ZipInputStream zippedInputStream = new ZipInputStream(uploaded.getInputStream());
			ZipEntry zipEntry = null;

			if ((zipEntry = zippedInputStream.getNextEntry()) != null) {

				String zipItemName = zipEntry.getName();

				logger.debug("Method unzipUploadedFile(): Zip entry [ " + zipItemName + " ]");

				if (zipEntry.isDirectory()) {
					throw new SpagoBIServiceException(getActionName(), "The uploaded file is a folder. Zip directly the file.");
				}

				DiskFileItemFactory factory = new DiskFileItemFactory();
				tempFileItem = factory.createItem(uploaded.getFieldName(), "application/octet-stream", uploaded.isFormField(), zipItemName);
				OutputStream tempFileItemOutStream = tempFileItem.getOutputStream();

				IOUtils.copy(zippedInputStream, tempFileItemOutStream);

				tempFileItemOutStream.close();
			}

			zippedInputStream.close();

			logger.debug("Method unzipUploadedFile(): End");
			return tempFileItem;

		} catch (Throwable t) {
			logger.error("Error while unzip file. Invalid archive file: " + t);
			throw new SpagoBIServiceException(getActionName(), "Error while unzip file. Invalid archive file", t);

		}
	}