List of usage examples for java.io BufferedOutputStream flush
@Override public synchronized void flush() throws IOException
From source file:it.greenvulcano.util.bin.BinaryUtils.java
/** * Write the content of a <code>byte</code> array into a file on the local * filesystem./*w ww . ja va 2s . co m*/ * * @param contentArray * the <code>byte</code> array to be written to file * @param filename * the name of the file to be written to * @param append * If true the data are appended to existent file * @throws IOException * if any I/O error occurs */ public static void writeBytesToFile(byte[] contentArray, String filename, boolean append) throws IOException { BufferedOutputStream bufOut = null; try { filename = TextUtils.adjustPath(filename); bufOut = new BufferedOutputStream(new FileOutputStream(filename, append), 10240); IOUtils.write(contentArray, bufOut); bufOut.flush(); } finally { if (bufOut != null) { bufOut.close(); } } }
From source file:org.bml.util.CompressUtils.java
/** * Extracts a zip | jar | war archive to the specified directory. * Uses the passed buffer size for read operations. * * @param zipFile// w ww .j a v a 2 s . c om * @param destDir * @param bufferSize * @throws IOException If there is an issue with the archive file or the file system. * @throws NullPointerException if any of the arguments are null. * @throws IllegalArgumentException if any of the arguments do not pass the * preconditions other than null tests. NOTE: This exception wil not be thrown * if this classes CHECKED member is set to false * * @pre zipFile!=null * @pre zipFile.exists() * @pre zipFile.canRead() * @pre zipFile.getName().matches("(.*[zZ][iI][pP])|(.*[jJ][aA][rR])") * * @pre destDir!=null * @pre destDir.exists() * @pre destDir.isDirectory() * @pre destDir.canWrite() * * @pre bufferSize > 0 */ public static void unzipFilesToPath(final File zipFile, final File destDir, final int bufferSize) throws IOException, IllegalArgumentException, NullPointerException { //zipFilePath.toLowerCase().endsWith(zipFilePath) if (CHECKED) { final String userName = User.getSystemUserName();//use cahced if possible //zipFile Preconditions.checkNotNull(zipFile, "Can not unzip null zipFile"); Preconditions.checkArgument(zipFile.getName().matches(ZIP_MIME_PATTERN), "Zip File at %s does not match the extensions allowed by the regex %s", zipFile, ZIP_MIME_PATTERN); Preconditions.checkArgument(zipFile.exists(), "Can not unzip file at %s. It does not exist.", zipFile); Preconditions.checkArgument(zipFile.canRead(), "Can not extract archive with no read permissions. Check File permissions. USER=%s FILE=%s", System.getProperty("user.name"), zipFile); //destDir Preconditions.checkNotNull(destDir, "Can not extract zipFileName=%s to a null destination", zipFile); Preconditions.checkArgument(destDir.isDirectory(), "Can not extract zipFileName %s to a destination %s that is not a directory", zipFile, destDir); Preconditions.checkArgument(destDir.exists(), "Can not extract zipFileName %s to a non existant destination %s", zipFile, destDir); Preconditions.checkArgument(destDir.canWrite(), "Can not extract archive with no write permissions. Check File permissions. USER=%s FILE=%s", System.getProperty("user.name"), destDir); //bufferSize Preconditions.checkArgument(bufferSize > 0, "Can not extract archive %s to %s with a buffer size less than 1 size = %s", zipFile, destDir, bufferSize); } final FileInputStream fileInputStream = new FileInputStream(zipFile); final ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream)); final String destBasePath = destDir.getAbsolutePath() + PATH_SEP; try { ZipEntry zipEntry; BufferedOutputStream destBufferedOutputStream; int byteCount; byte[] data; while ((zipEntry = zipInputStream.getNextEntry()) != null) { destBufferedOutputStream = new BufferedOutputStream( new FileOutputStream(destBasePath + zipEntry.getName()), bufferSize); data = new byte[bufferSize]; while ((byteCount = zipInputStream.read(data, 0, bufferSize)) != -1) { destBufferedOutputStream.write(data, 0, byteCount); } destBufferedOutputStream.flush(); destBufferedOutputStream.close(); } fileInputStream.close(); zipInputStream.close(); } catch (IOException ioe) { if (LOG.isWarnEnabled()) { LOG.warn(String.format("IOException caught while unziping archive %s to %s", zipFile, destDir), ioe); } throw ioe; } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(zipInputStream); } }
From source file:Main.java
public static void compressAFileToZip(File zip, File source) throws IOException { Log.d("source: " + source.getAbsolutePath(), ", length: " + source.length()); Log.d("zip:", zip.getAbsolutePath()); zip.getParentFile().mkdirs();/*from w ww . j a v a 2s .c om*/ File tempFile = new File(zip.getAbsolutePath() + ".tmp"); FileOutputStream fos = new FileOutputStream(tempFile); BufferedOutputStream bos = new BufferedOutputStream(fos); ZipOutputStream zos = new ZipOutputStream(bos); ZipEntry zipEntry = new ZipEntry(source.getName()); zipEntry.setTime(source.lastModified()); zos.putNextEntry(zipEntry); FileInputStream fis = new FileInputStream(source); BufferedInputStream bis = new BufferedInputStream(fis); byte[] bArr = new byte[4096]; int byteRead = 0; while ((byteRead = bis.read(bArr)) != -1) { zos.write(bArr, 0, byteRead); } zos.flush(); zos.closeEntry(); zos.close(); Log.d("zipEntry: " + zipEntry, "compressedSize: " + zipEntry.getCompressedSize()); bos.flush(); fos.flush(); bos.close(); fos.close(); bis.close(); fis.close(); zip.delete(); tempFile.renameTo(zip); }
From source file:com.aurel.track.lucene.util.FileUtil.java
public static void unzipFile(File uploadZip, File unzipDestinationDirectory) throws IOException { if (!unzipDestinationDirectory.exists()) { unzipDestinationDirectory.mkdirs(); }/*from ww w . j a v a2 s. co m*/ final int BUFFER = 2048; // Open Zip file for reading ZipFile zipFile = new ZipFile(uploadZip, ZipFile.OPEN_READ); // Create an enumeration of the entries in the zip file Enumeration zipFileEntries = zipFile.entries(); // Process each entry while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(unzipDestinationDirectory, currentEntry); // grab file's parent directory structure File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed destinationParent.mkdirs(); // extract file if not a directory if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; // write the current file to disk FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); // read and write until last byte is encountered while ((currentByte = is.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); dest.close(); is.close(); } } zipFile.close(); }
From source file:com.atlassian.jira.util.IOUtil.java
/** * Copy bytes from an <code>InputStream</code> to an * <code>OutputStream</code>, with buffering. * This is equivalent to passing a//from www . j ava 2s . c o m * {@link java.io.BufferedInputStream} and * {@link java.io.BufferedOutputStream} to {@link #copy(InputStream, OutputStream)}, * and flushing the output stream afterwards. The streams are not closed * after the copy. * @deprecated Buffering streams is actively harmful! See the class description as to why. Use * {@link #copy(InputStream, OutputStream)} instead. */ public static void bufferedCopy(final InputStream input, final OutputStream output) throws IOException { final BufferedInputStream in = new BufferedInputStream(input); final BufferedOutputStream out = new BufferedOutputStream(output); copy(in, out); out.flush(); }
From source file:Main.java
public static boolean copyAssetFile(Context context, String originFileName, String destFilePath, String destFileName) {/*from www .j a v a2 s . co m*/ InputStream is = null; BufferedOutputStream bos = null; try { is = context.getAssets().open(originFileName); File destPathFile = new File(destFilePath); if (!destPathFile.exists()) { destPathFile.mkdirs(); } File destFile = new File(destFilePath + File.separator + destFileName); if (!destFile.exists()) { destFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(destFile); bos = new BufferedOutputStream(fos); byte[] buffer = new byte[256]; int length = 0; while ((length = is.read(buffer)) > 0) { bos.write(buffer, 0, length); } bos.flush(); return true; } catch (Exception ex) { ex.printStackTrace(); } finally { if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != bos) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; }
From source file:Main.java
public static void downloadImage(String imageUrl) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { Log.d("TAG", "monted sdcard"); } else {//w w w . j a v a2s . c om Log.d("TAG", "has no sdcard"); } HttpURLConnection con = null; FileOutputStream fos = null; BufferedOutputStream bos = null; BufferedInputStream bis = null; File imageFile = null; try { URL url = new URL(imageUrl); con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(5 * 1000); con.setReadTimeout(15 * 1000); con.setDoInput(true); con.setDoOutput(true); bis = new BufferedInputStream(con.getInputStream()); imageFile = new File(getImagePath(imageUrl)); fos = new FileOutputStream(imageFile); bos = new BufferedOutputStream(fos); byte[] b = new byte[1024]; int length; while ((length = bis.read(b)) != -1) { bos.write(b, 0, length); bos.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } if (con != null) { con.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } if (imageFile != null) { } }
From source file:CB_Core.Api.PocketQuery.java
/** * @param AccessToken//from w w w . j a va2s.c om * Config.GetAccessToken(true) * @param pocketQueryConfig * Config.settings.PocketQueryFolder.getValue() * @param PqFolder * @return */ public static int DownloadSinglePocketQuery(PQ pocketQuery, String PqFolder) { HttpGet httpGet = new HttpGet( GroundspeakAPI.GS_LIVE_URL + "GetPocketQueryZippedFile?format=json&AccessToken=" + GroundspeakAPI.GetAccessToken(true) + "&PocketQueryGuid=" + pocketQuery.GUID); try { // String result = GroundspeakAPI.Execute(httpGet); httpGet.setHeader("Accept", "application/json"); httpGet.setHeader("Content-type", "application/json"); // Execute HTTP Post Request String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpGet); int buffLen = 32 * 1024; byte[] buff = new byte[buffLen]; InputStream inputStream = response.getEntity().getContent(); int buffCount = inputStream.read(buff, 0, buffLen); int buffPos = 0; result = ""; // now read from the response until the ZIP Informations are beginning or to the end of stream for (int i = 0; i < buffCount; i++) { byte c = buff[i]; result += (char) c; if (result.contains("\"ZippedFile\":\"")) { // The stream position represents the beginning of the ZIP block // to have a correct JSON Array we must add a "}} to the // result result += "\"}}"; buffPos = i; // Position im Buffer, an der die ZIP-Infos beginnen break; } } // try // Parse JSON Result { JSONTokener tokener = new JSONTokener(result); JSONObject json = (JSONObject) tokener.nextValue(); JSONObject status = json.getJSONObject("Status"); if (status.getInt("StatusCode") == 0) { GroundspeakAPI.LastAPIError = ""; SimpleDateFormat postFormater = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = postFormater.format(pocketQuery.DateLastGenerated); String local = PqFolder + "/" + pocketQuery.Name + "_" + dateString + ".zip"; // String test = json.getString("ZippedFile"); FileOutputStream fs; fs = new FileOutputStream(local); BufferedOutputStream bfs = new BufferedOutputStream(fs); try { // int firstZipPos = result.indexOf("\"ZippedFile\":\"") + 14; // int lastZipPos = result.indexOf("\"", firstZipPos + 1) - 1; CB_Utils.Converter.Base64.decodeStreamToStream(inputStream, buff, buffLen, buffCount, buffPos, bfs); } catch (Exception ex) { } // fs.write(resultByte); bfs.flush(); bfs.close(); fs.close(); result = null; System.gc(); return 0; } else { GroundspeakAPI.LastAPIError = ""; GroundspeakAPI.LastAPIError = "StatusCode = " + status.getInt("StatusCode") + "\n"; GroundspeakAPI.LastAPIError += status.getString("StatusMessage") + "\n"; GroundspeakAPI.LastAPIError += status.getString("ExceptionDetails"); return (-1); } } catch (JSONException e) { e.printStackTrace(); } } catch (ClientProtocolException e) { System.out.println(e.getMessage()); return (-1); } catch (IOException e) { System.out.println(e.getMessage()); return (-1); } return 0; }
From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java
public static void saveFile(String foldername, String filename, InputStream input) throws IOException { // LogWriter log = LogWriter.getInstance(); if (filename == null) { filename = File.createTempFile("xx", ".out").getName(); //$NON-NLS-1$ //$NON-NLS-2$ }/*from w w w. jav a 2 s . c o m*/ // Do no overwrite existing file File file = new File(foldername, filename); for (int i = 0; file.exists(); i++) { file = new File(foldername, filename + i); } FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedInputStream bis = new BufferedInputStream(input); int aByte; while ((aByte = bis.read()) != -1) { bos.write(aByte); } bos.flush(); bos.close(); bis.close(); }
From source file:com.zlfun.framework.excel.ExcelUtils.java
public static <T> void save(String fileName, String sheetName, Class<T> clazz, List<T> list) { try {/*ww w. j a v a 2 s .c o m*/ //? BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(fileName)); write(sheetName, clazz, list, os); os.flush(); os.close(); } catch (UnsupportedEncodingException ex) { Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex); } }