java.io.BufferedOutputStream Java Examples

The following examples show how to use java.io.BufferedOutputStream. 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: CompressTools.java    From MyBox with Apache License 2.0 7 votes vote down vote up
public static File decompress(CompressorInputStream compressorInputStream, File targetFile) {
        try {
            if (compressorInputStream == null) {
                return null;
            }
            File file = (targetFile == null) ? FileTools.getTempFile() : targetFile;
            if (file.exists()) {
                file.delete();
            }
            try ( BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
                final byte[] buf = new byte[CommonValues.IOBufferLength];
                int len = -1;
                while (-1 != (len = compressorInputStream.read(buf))) {
                    out.write(buf, 0, len);
                }
            }
            return file;
        } catch (Exception e) {
//            logger.debug(e.toString());
            return null;
        }
    }
 
Example #2
Source File: HprofParser.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse a java heap dump file
 *
 * @param dump Heap dump file to parse
 * @param debug Turn on/off debug file parsing
 * @param callStack Turn on/off tracking of object allocation call stack
 * @param calculateRefs Turn on/off tracking object allocation call stack
 * @throws Exception
 * @return File containing output from the parser
 */
public static File parse(File dump, boolean debug, boolean callStack, boolean calculateRefs) throws Exception {
    File out = new File("hprof." + System.currentTimeMillis() + ".out");
    if (out.exists()) {
        out.delete();
    }

    PrintStream psSystemOut = System.out;
    try (PrintStream psHprof = new PrintStream(new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath())))) {
        System.setOut(psHprof);

        int debugLevel = debug ? 2 : 0;
        try (Snapshot snapshot = Reader.readFile(dump.getAbsolutePath(), callStack, debugLevel)) {
            System.out.println("Snapshot read, resolving...");
            snapshot.resolve(calculateRefs);
            System.out.println("Snapshot resolved.");
        }
   } finally {
       System.setOut(psSystemOut);
   }

    return out;
}
 
Example #3
Source File: LruDiskCache.java    From candybar with Apache License 2.0 6 votes vote down vote up
@Override
public boolean save(String imageUri, Bitmap bitmap) throws IOException {
    DiskLruCache.Editor editor = cache.edit(getKey(imageUri));
    if (editor == null) {
        return false;
    }

    OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), bufferSize);
    boolean savedSuccessfully = false;
    try {
        savedSuccessfully = bitmap.compress(compressFormat, compressQuality, os);
    } finally {
        IoUtils.closeSilently(os);
    }
    if (savedSuccessfully) {
        editor.commit();
    } else {
        editor.abort();
    }
    return savedSuccessfully;
}
 
Example #4
Source File: FileUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 保存文件
 * @param file 文件
 * @param data 待存储数据
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveFile(final File file, final byte[] data) {
    if (file != null && data != null) {
        try {
            // 防止文件夹没创建
            createFolder(getDirName(file));
            // 写入文件
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(data);
            bos.close();
            fos.close();
            return true;
        } catch (Exception e) {
            JCLogUtils.eTag(TAG, e, "saveFile");
        }
    }
    return false;
}
 
Example #5
Source File: FileUtil.java    From FaceDemo with Apache License 2.0 6 votes vote down vote up
/**
 * 保存一个暂时的bitmap图片
 *
 * 保存目录在
 * @param b
 */
public static String saveTmpBitmap(Bitmap b,String name){
    String result= "";
    String jpegName = MyConfig.ROOT_CACHE+File.separator+MyConfig.FACE_DIR +File.separator+name +".jpg";
    Log.d("FileUtil",jpegName);
    result = jpegName;
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100 , bos);
        bos.flush();
        bos.close();
        Log.i(TAG, "暂存的 saveBitmap成功");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i(TAG, "暂存的saveBitmap失败");
        e.printStackTrace();
    }
    return result;
}
 
Example #6
Source File: VisualGraphTopComponent.java    From constellation with Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground() throws Exception {
    final ReadableGraph rg = graph.getReadableGraph();
    try {
        copy = rg.copy();
    } finally {
        rg.release();
    }
    try {
        try (OutputStream out = new BufferedOutputStream(freshGdo.getPrimaryFile().getOutputStream())) {
            // Write the graph.
            cancelled = new GraphJsonWriter().writeGraphToZip(copy, out, new HandleIoProgress("Writing..."));
        }
        SaveNotification.saved(freshGdo.getPrimaryFile().getPath());
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    return null;
}
 
Example #7
Source File: BinaryDictionaryFileDumper.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Copies the data in an input stream to a target file if the magic number matches.
 *
 * If the magic number does not match the expected value, this method throws an
 * IOException. Other usual conditions for IOException or FileNotFoundException
 * also apply.
 *
 * @param input the stream to be copied.
 * @param output an output stream to copy the data to.
 */
public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
        final BufferedOutputStream output) throws IOException {
    // Check the magic number
    final int length = MAGIC_NUMBER_VERSION_2.length;
    final byte[] magicNumberBuffer = new byte[length];
    final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
    if (readMagicNumberSize < length) {
        throw new IOException("Less bytes to read than the magic number length");
    }
    if (SHOULD_VERIFY_MAGIC_NUMBER) {
        if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
            if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
                throw new IOException("Wrong magic number for downloaded file");
            }
        }
    }
    output.write(magicNumberBuffer);

    // Actually copy the file
    final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
    for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) {
        output.write(buffer, 0, readBytes);
    }
    input.close();
}
 
Example #8
Source File: ImportTask.java    From apkextractor with GNU General Public License v3.0 6 votes vote down vote up
private void unZipToFile(ZipInputStream zipInputStream,String entryPath) throws Exception{
    File folder=new File(StorageUtil.getMainExternalStoragePath()+"/"+entryPath.substring(0,entryPath.lastIndexOf("/")));
    if(!folder.exists())folder.mkdirs();
    String writePath=StorageUtil.getMainExternalStoragePath()+"/"+entryPath;
    File writeFile=new File(writePath);
    OutputStream outputStream=new BufferedOutputStream(new FileOutputStream(writeFile));
    currentWritePath=writePath;
    currentWrtingFileItem=new FileItem(writeFile);
    byte [] buffer=new byte[1024];
    int len;
    while ((len=zipInputStream.read(buffer))!=-1&&!isInterrupted){
        outputStream.write(buffer,0,len);
        progress+=len;
        checkSpeedAndPostToCallback(len);
        checkProgressAndPostToCallback();
    }
    outputStream.flush();
    outputStream.close();
    if(!isInterrupted)currentWrtingFileItem=null;
}
 
Example #9
Source File: GeneralConfMaker.java    From yosegi with Apache License 2.0 6 votes vote down vote up
@Override
public void write( final Map<String,String> settingContainer ,
    final String outputPath , final boolean overwrite ) throws IOException {
  File targetFile = new File( outputPath );
  if ( targetFile.exists() ) {
    if ( overwrite ) {
      if ( ! targetFile.delete() ) {
        throw new IOException( "Could not remove file. Target : " + outputPath );
      }
    } else {
      throw new IOException( "Output file is already exists. Target : " + outputPath );
    }
  }

  OutputStream out = new BufferedOutputStream( new FileOutputStream( outputPath ) );
  write( settingContainer , out );
}
 
Example #10
Source File: FileHelper.java    From imsdk-android with MIT License 6 votes vote down vote up
public static boolean inputStreamToFile(InputStream inputStream, String filename, String tmpSuffix) throws IOException {

        BufferedInputStream bis = new BufferedInputStream(inputStream);
        // 存储加临时后缀,避免重名
        File file = new File(filename + tmpSuffix);
        File parent = file.getParentFile();
        if (parent != null && (!parent.exists())) {
            parent.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(file);
        BufferedOutputStream bos = new BufferedOutputStream(fos, CACHED_SIZE);
        int count;
        byte data[] = new byte[CACHED_SIZE];
        while ((count = bis.read(data, 0, CACHED_SIZE)) != -1) {
            bos.write(data, 0, count);
        }
        bos.flush();
        bos.close();
        bis.close();

        return renameFile(file, filename);
    }
 
Example #11
Source File: ZipUtil.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
public static void decompress(final String sourceFile, final String outputDir, final Checksum checksum)
                                                                                                       throws IOException {
    try (final FileInputStream fis = new FileInputStream(sourceFile);
            final CheckedInputStream cis = new CheckedInputStream(fis, checksum);
            final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cis))) {
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            final String fileName = entry.getName();
            final File entryFile = new File(Paths.get(outputDir, fileName).toString());
            FileUtils.forceMkdir(entryFile.getParentFile());
            try (final FileOutputStream fos = new FileOutputStream(entryFile);
                    final BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                IOUtils.copy(zis, bos);
                bos.flush();
                fos.getFD().sync();
            }
        }
        // Continue to read all remaining bytes(extra metadata of ZipEntry) directly from the checked stream,
        // Otherwise, the checksum value maybe unexpected.
        //
        // See https://coderanch.com/t/279175/java/ZipInputStream
        IOUtils.copy(cis, NullOutputStream.NULL_OUTPUT_STREAM);
    }
}
 
Example #12
Source File: Injector.java    From deployment-examples with MIT License 6 votes vote down vote up
/** Publish generated events to a file. */
public static void publishDataToFile(String fileName, int numMessages, int delayInMillis)
    throws IOException {
  PrintWriter out =
      new PrintWriter(
          new OutputStreamWriter(
              new BufferedOutputStream(new FileOutputStream(fileName, true)), "UTF-8"));

  try {
    for (int i = 0; i < Math.max(1, numMessages); i++) {
      Long currTime = System.currentTimeMillis();
      String message = generateEvent(currTime, delayInMillis);
      out.println(message);
    }
  } catch (Exception e) {
    System.err.print("Error in writing generated events to file");
    e.printStackTrace();
  } finally {
    out.flush();
    out.close();
  }
}
 
Example #13
Source File: BandStructure.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static OutputStream getDumpStream(String name, int seq, String ext, Object b) throws IOException {
    if (dumpDir == null) {
        dumpDir = File.createTempFile("BD_", "", new File("."));
        dumpDir.delete();
        if (dumpDir.mkdir())
            Utils.log.info("Dumping bands to "+dumpDir);
    }
    name = name.replace('(', ' ').replace(')', ' ');
    name = name.replace('/', ' ');
    name = name.replace('*', ' ');
    name = name.trim().replace(' ','_');
    name = ((10000+seq) + "_" + name).substring(1);
    File dumpFile = new File(dumpDir, name+ext);
    Utils.log.info("Dumping "+b+" to "+dumpFile);
    return new BufferedOutputStream(new FileOutputStream(dumpFile));
}
 
Example #14
Source File: PersistentDataStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void save() {
    final FileOutputStream os;
    try {
        os = mAtomicFile.startWrite();
        boolean success = false;
        try {
            XmlSerializer serializer = new FastXmlSerializer();
            serializer.setOutput(new BufferedOutputStream(os), StandardCharsets.UTF_8.name());
            saveToXml(serializer);
            serializer.flush();
            success = true;
        } finally {
            if (success) {
                mAtomicFile.finishWrite(os);
            } else {
                mAtomicFile.failWrite(os);
            }
        }
    } catch (IOException ex) {
        Slog.w(InputManagerService.TAG, "Failed to save input manager persistent store data.", ex);
    }
}
 
Example #15
Source File: FileUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 保存文件
 * @param file 文件
 * @param data 待存储数据
 * @return {@code true} success, {@code false} fail
 */
public static boolean saveFile(final File file, final byte[] data) {
    if (file != null && data != null) {
        try {
            // 防止文件夹没创建
            createFolder(getDirName(file));
            // 写入文件
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(data);
            bos.close();
            fos.close();
            return true;
        } catch (Exception e) {
            JCLogUtils.eTag(TAG, e, "saveFile");
        }
    }
    return false;
}
 
Example #16
Source File: FileUtil.java    From EasyPhotos with Apache License 2.0 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "IMG_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #17
Source File: FileUtil.java    From AlbumCameraRecorder with MIT License 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #18
Source File: ZipUtilities.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Zip a bytearray
 * 
 * @param data
 * @return
 * @throws IOException
 */
public static byte[] zip(byte[] data, String entryFileName) throws IOException {
	try(final ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
		try(final ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outStream))) {
			
			if (data != null) {
				addFileDataToOpenZipFileStream(data, entryFileName, zipOutputStream);
			}
			
		}
		
		outStream.flush();
		
		return outStream.toByteArray();
	}
}
 
Example #19
Source File: ManagerServlet.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Upload the WAR file included in this request, and store it at the
 * specified file location.
 *
 * @param writer    Writer to render to
 * @param request   The servlet request we are processing
 * @param war       The file into which we should store the uploaded WAR
 * @param smClient  The StringManager used to construct i18n messages based
 *                  on the Locale of the client
 *
 * @exception IOException if an I/O error occurs during processing
 */
protected void uploadWar(PrintWriter writer, HttpServletRequest request,
        File war, StringManager smClient) throws IOException {

    if (war.exists() && !war.delete()) {
        String msg = smClient.getString("managerServlet.deleteFail", war);
        throw new IOException(msg);
    }

    try (ServletInputStream istream = request.getInputStream();
            BufferedOutputStream ostream =
                    new BufferedOutputStream(new FileOutputStream(war), 1024)) {
        byte buffer[] = new byte[1024];
        while (true) {
            int n = istream.read(buffer);
            if (n < 0) {
                break;
            }
            ostream.write(buffer, 0, n);
        }
    } catch (IOException e) {
        if (war.exists() && !war.delete()) {
            writer.println(
                    smClient.getString("managerServlet.deleteFail", war));
        }
        throw e;
    }

}
 
Example #20
Source File: UnboundSSLUtils.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void connect() throws IOException {
    System.out.println("Client: connect to server");
    try (BufferedInputStream bis = new BufferedInputStream(
                    socket.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(
                    socket.getOutputStream())) {

        for (byte[] bytes : arrays) {
            System.out.println("Client: send byte array: "
                    + Arrays.toString(bytes));

            bos.write(bytes);
            bos.flush();

            byte[] recieved = new byte[bytes.length];
            int read = bis.read(recieved, 0, bytes.length);
            if (read < 0) {
                throw new IOException("Client: couldn't read a response");
            }

            System.out.println("Client: recieved byte array: "
                    + Arrays.toString(recieved));

            if (!Arrays.equals(bytes, recieved)) {
                throw new IOException("Client: sent byte array "
                            + "is not equal with recieved byte array");
            }
        }
        socket.getSession().invalidate();
    } finally {
        if (!socket.isClosed()) {
            socket.close();
        }
    }
}
 
Example #21
Source File: OptimisticTypesPersistence.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Stores the map of optimistic types for a given function.
 * @param locationDescriptor the opaque persistence location descriptor, retrieved by calling
 * {@link #getLocationDescriptor(Source, int, Type[])}.
 * @param optimisticTypes the map of optimistic types.
 */
@SuppressWarnings("resource")
public static void store(final Object locationDescriptor, final Map<Integer, Type> optimisticTypes) {
    if(locationDescriptor == null || optimisticTypes.isEmpty()) {
        return;
    }
    final File file = ((LocationDescriptor)locationDescriptor).file;

    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            synchronized(getFileLock(file)) {
                if (!file.exists()) {
                    // If the file already exists, we aren't increasing the number of cached files, so
                    // don't schedule cleanup.
                    scheduleCleanup();
                }
                try (final FileOutputStream out = new FileOutputStream(file)) {
                    out.getChannel().lock(); // lock exclusive
                    final DataOutputStream dout = new DataOutputStream(new BufferedOutputStream(out));
                    Type.writeTypeMap(optimisticTypes, dout);
                    dout.flush();
                } catch(final Exception e) {
                    reportError("write", file, e);
                }
            }
            return null;
        }
    });
}
 
Example #22
Source File: LogFile.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
Writer(@NonNull byte[] secret, @NonNull File file) throws IOException {
  this.secret       = secret;
  this.file         = file;
  this.outputStream = new BufferedOutputStream(new FileOutputStream(file, true));

  try {
    this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example #23
Source File: ExternalFileConfigurationEditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Helper method trying to ensure that the file location provided by the user
 * exists. If that is not the case it prompts the user if an empty
 * configuration file should be created.
 *
 * @param location
 *          the configuration file location
 * @throws CheckstylePluginException
 *           error when trying to ensure the location file existance
 */
private boolean ensureFileExists(String location) throws CheckstylePluginException {

  // support dynamic location strings
  String resolvedLocation = ExternalFileConfigurationType.resolveDynamicLocation(location);

  File file = new File(resolvedLocation);
  if (!file.exists()) {
    boolean confirm = MessageDialog.openQuestion(mBtnBrowse.getShell(),
            Messages.ExternalFileConfigurationEditor_titleFileDoesNotExist,
            Messages.ExternalFileConfigurationEditor_msgFileDoesNotExist);
    if (confirm) {

      if (file.getParentFile() != null) {
        file.getParentFile().mkdirs();
      }

      try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
        ConfigurationWriter.writeNewConfiguration(out, mWorkingCopy);
      } catch (IOException ioe) {
        CheckstylePluginException.rethrow(ioe);
      }
      return true;
    }
    return false;
  }

  return true;
}
 
Example #24
Source File: LocalFileRoleAccessor.java    From incubator-iotdb with Apache License 2.0 5 votes vote down vote up
@Override
public void saveRole(Role role) throws IOException {
  File roleProfile = SystemFileFactory.INSTANCE.getFile(
      roleDirPath + File.separator + role.getName() + IoTDBConstant.PROFILE_SUFFIX + TEMP_SUFFIX);
  try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(roleProfile))) {
    try {
      IOUtils.writeString(outputStream, role.getName(), STRING_ENCODING, encodingBufferLocal);

      role.getPrivilegeList().sort(PathPrivilege.REFERENCE_DESCENT_SORTER);
      int privilegeNum = role.getPrivilegeList().size();
      IOUtils.writeInt(outputStream, privilegeNum, encodingBufferLocal);
      for (int i = 0; i < privilegeNum; i++) {
        PathPrivilege pathPrivilege = role.getPrivilegeList().get(i);
        IOUtils
            .writePathPrivilege(outputStream, pathPrivilege, STRING_ENCODING,
                encodingBufferLocal);
      }
      outputStream.flush();
    } catch (Exception e) {
      throw new IOException(e);
    }
  }

  File oldFile = SystemFileFactory.INSTANCE.getFile(
      roleDirPath + File.separator + role.getName() + IoTDBConstant.PROFILE_SUFFIX);
  IOUtils.replaceFile(roleProfile, oldFile);
}
 
Example #25
Source File: CommonUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static void zip(ZipOutputStream out, BufferedOutputStream bos, File srcFile, String base) throws Exception {
    //如果路径为目录(文件夹)
    if (srcFile.isDirectory()) {
        //取出文件夹中的文件(或子文件夹)
        File[] flist = srcFile.listFiles();
        if (null == flist || flist.length == 0) {
            //如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
            out.putNextEntry(new ZipEntry(base + "/"));
        } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
        {
            for (int i = 0; i < flist.length; i++) {
                zip(out, bos, flist[i], base + "/" + flist[i].getName());
            }
        }
    } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
    {
        out.putNextEntry(new ZipEntry(base));
        FileInputStream fos = new FileInputStream(srcFile);
        BufferedInputStream bis = new BufferedInputStream(fos);
        int tag;
        //将源文件写入到zip文件中
        while ((tag = bis.read()) != -1) {
            bos.write(tag);
        }
        bis.close();
        fos.close();
    }
}
 
Example #26
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/1399432
 */
public static void zip(File directory, File zipfile) throws Exception {
    if (directory.listFiles() == null || directory.listFiles().length == 0) {
        return;
    }
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<File>();
    queue.push(directory);
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipfile)));
    try {
        while (!queue.isEmpty()) {
            directory = queue.pop();
            for (File path : directory.listFiles()) {
                String name = base.relativize(path.toURI()).getPath();
                if (path.isDirectory()) {
                    queue.push(path);
                    name = name.endsWith("/") ? name : name + "/";
                    out.putNextEntry(new ZipEntry(name));
                } else {
                    out.putNextEntry(new ZipEntry(name));
                    copy(path, out);
                    out.closeEntry();
                }
            }
        }
    } finally {
        out.close();
    }
}
 
Example #27
Source File: XMLWriter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a writer for the specified encoding based on an output stream.
 *
 * @param output The output stream
 * @param encoding The encoding
 * @return A suitable writer
 * @throws UnsupportedEncodingException There is no convertor to support
 * this encoding
 */
private Writer getWriter(OutputStream output, String encoding, Charset cs)
    throws XMLStreamException, UnsupportedEncodingException
{
    if (cs != null) {
        return (new OutputStreamWriter(new BufferedOutputStream(output), cs));
    }

    return new OutputStreamWriter(new BufferedOutputStream(output), encoding);
}
 
Example #28
Source File: Utils.java    From Injector with Apache License 2.0 5 votes vote down vote up
public static void unzip(File zipFile, String destDirectory) throws IOException {
	File destDir = new File(destDirectory);
	if (!destDir.exists()) {
		destDir.mkdirs();
	}
	ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
	ZipEntry entry = zipIn.getNextEntry();
	while (entry != null) {
		String filePath = destDirectory + File.separator + entry.getName();
		if (!entry.isDirectory()) {
			File destinationFile = new File(filePath);
			destinationFile.createNewFile();
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile));
			byte[] bytesIn = new byte[4096];
			int read;
			while ((read = zipIn.read(bytesIn)) != -1) {
				bos.write(bytesIn, 0, read);
			}
			bos.close();
		} else {
			File dir = new File(filePath);
			dir.mkdir();
		}
		zipIn.closeEntry();
		entry = zipIn.getNextEntry();
	}
	zipIn.close();
}
 
Example #29
Source File: StandardDocFileFactory.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open an output stream for the file.
 * The file must have been created with a location of
 * {@link DocumentationTool.Location#DOCUMENTATION_OUTPUT} and a corresponding relative path.
 */
public OutputStream openOutputStream() throws IOException, UnsupportedEncodingException {
    if (location != DocumentationTool.Location.DOCUMENTATION_OUTPUT)
        throw new IllegalStateException();

    OutputStream out = getFileObjectForOutput(path).openOutputStream();
    return new BufferedOutputStream(out);
}
 
Example #30
Source File: AuFileWriter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }