List of usage examples for java.io BufferedOutputStream write
@Override public synchronized void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this buffered output stream. From source file:fridgegameinstaller.installation.java
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = zipIn.read(bytesIn)) != -1) { bos.write(bytesIn, 0, read); }//from w w w . j a v a 2s . co m bos.close(); }
From source file:com.sun.identity.security.cert.AMCRLStore.java
private byte[] getCRLByHttpURI(String url) { String argString = ""; //default StringBuffer params = null;//from w ww .j a v a2 s. c om HttpURLConnection con = null; byte[] crl = null; String uriParamsCRL = storeParam.getURIParams(); try { if (uriParamsCRL != null) { params = new StringBuffer(); StringTokenizer st1 = new StringTokenizer(uriParamsCRL, ","); while (st1.hasMoreTokens()) { String token = st1.nextToken(); StringTokenizer st2 = new StringTokenizer(token, "="); if (st2.countTokens() == 2) { String param = st2.nextToken(); String value = st2.nextToken(); params.append(URLEncDec.encode(param) + "=" + URLEncDec.encode(value)); } else { continue; } if (st1.hasMoreTokens()) { params.append("&"); } } } URL uri = new URL(url); con = HttpURLConnectionManager.getConnection(uri); // Prepare for both input and output con.setDoInput(true); // Turn off Caching con.setUseCaches(false); if (params != null) { byte[] paramsBytes = params.toString().trim().getBytes("UTF-8"); if (paramsBytes.length > 0) { con.setDoOutput(true); con.setRequestProperty("Content-Length", Integer.toString(paramsBytes.length)); // Write the arguments as post data BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); out.write(paramsBytes, 0, paramsBytes.length); out.flush(); out.close(); } } // Input ... InputStream in = con.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf, 0, buf.length)) != -1) { bos.write(buf, 0, len); } crl = bos.toByteArray(); if (debug.messageEnabled()) { debug.message("AMCRLStore.getCRLByHttpURI: crl.length = " + crl.length); } } catch (Exception e) { debug.error("getCRLByHttpURI : Error in getting CRL", e); } return crl; }
From source file:com.jeson.xutils.http.callback.FileDownloadHandler.java
public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target, boolean isResume, String responseFileName) throws IOException { if (entity == null || TextUtils.isEmpty(target)) { return null; }/*from www. j a va 2s . c om*/ Log.e("target", " target:" + target); File targetFile = new File(target); Log.e("target", " targetFile:" + targetFile); if (!targetFile.exists()) { File dir = targetFile.getParentFile(); if (dir.exists() || dir.mkdirs()) { targetFile.createNewFile(); } } long current = 0; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { FileOutputStream fileOutputStream = null; if (isResume) { current = targetFile.length(); fileOutputStream = new FileOutputStream(target, true); } else { fileOutputStream = new FileOutputStream(target); } long total = entity.getContentLength() + current; bis = new BufferedInputStream(entity.getContent()); bos = new BufferedOutputStream(fileOutputStream); if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) { return targetFile; } byte[] tmp = new byte[4096]; int len; while ((len = bis.read(tmp)) != -1) { bos.write(tmp, 0, len); current += len; if (callBackHandler != null) { if (!callBackHandler.updateProgress(total, current, false)) { return targetFile; } } } bos.flush(); if (callBackHandler != null) { callBackHandler.updateProgress(total, current, true); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); } if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) { File newFile = new File(targetFile.getParent(), responseFileName); while (newFile.exists()) { newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName); } return targetFile.renameTo(newFile) ? newFile : targetFile; } else { return targetFile; } }
From source file:cn.isif.util_plus.http.callback.FileDownloadHandler.java
public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target, boolean isResume, String responseFileName) throws IOException { if (entity == null || TextUtils.isEmpty(target)) { return null; }/*from w ww.ja v a 2s . co m*/ File targetFile = new File(target); if (!targetFile.exists()) { File dir = targetFile.getParentFile(); if (dir.exists() || dir.mkdirs()) { targetFile.createNewFile(); } } long current = 0; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { FileOutputStream fileOutputStream = null; if (isResume) { current = targetFile.length(); fileOutputStream = new FileOutputStream(target, true); } else { fileOutputStream = new FileOutputStream(target); } long total = entity.getContentLength() + current; bis = new BufferedInputStream(entity.getContent()); bos = new BufferedOutputStream(fileOutputStream); if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) { return targetFile; } byte[] tmp = new byte[4096]; int len; while ((len = bis.read(tmp)) != -1) { bos.write(tmp, 0, len); current += len; if (callBackHandler != null) { if (!callBackHandler.updateProgress(total, current, false)) { return targetFile; } } } bos.flush(); if (callBackHandler != null) { callBackHandler.updateProgress(total, current, true); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); } if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) { File newFile = new File(targetFile.getParent(), responseFileName); while (newFile.exists()) { newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName); } return targetFile.renameTo(newFile) ? newFile : targetFile; } else { return targetFile; } }
From source file:com.connection.factory.SftpConnectionApacheLib.java
@Override public boolean downloadFile(String fullLocalPad, String fullRemotePath) { File file = new File(fullLocalPad); InputStream input = null;/* w w w . j av a2 s. co m*/ BufferedOutputStream output = null; try { input = command.get(fullRemotePath); if (input == null) { return false; } } catch (SftpException ex) { if (file.exists()) { file.delete(); } return false; } try { output = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytesArray = new byte[CURRENT_FILE_BYTE_BUFFER]; int bytesRead = -1; while ((bytesRead = input.read(bytesArray)) != -1) { output.write(bytesArray, 0, bytesRead); output.flush(); } output.close(); input.close(); return true; } catch (IOException ex) { if (file.exists()) { file.delete(); } return false; } }
From source file:fr.gouv.finances.cp.xemelios.importers.batch.BatchRealImporter.java
private ImportContent files(final String extension, final String titreEtat) { ImportContent ic = new ImportContent(); Vector<File> ret = new Vector<File>(); ret.addAll(files);//from w w w .j a v a 2 s.c om // on regarde si l'un des fichiers a importer est un zip for (int i = 0; i < ret.size(); i++) { if (ret.get(i).getName().toLowerCase().endsWith(".zip")) { if (ret.get(i).exists()) { ZipFile zf = null; try { zf = new ZipFile(ret.get(i)); for (Enumeration<? extends ZipEntry> enumer = zf.entries(); enumer.hasMoreElements();) { ZipEntry ze = enumer.nextElement(); if (!ze.isDirectory()) { String fileName = ze.getName(); String entryName = fileName.toLowerCase(); fileName = fileName.replace(File.pathSeparatorChar, '_') .replace(File.separatorChar, '_').replace(':', '|').replace('\'', '_') .replace('/', '_'); logger.debug(entryName); if (PJRef.isPJ(ze)) { PJRef pj = new PJRef(ze); File tmpFile = pj.writeTmpFile(FileUtils.getTempDir(), zf); ic.pjs.add(pj); filesToDrop.add(tmpFile); } else if ((entryName.endsWith(extension.toLowerCase()) || entryName.endsWith(".xml")) && !fileName.startsWith("_")) { // on decompresse le fichier dans le // repertoire temporaire, comme ca il sera // supprime en quittant InputStream is = zf.getInputStream(ze); BufferedInputStream bis = new BufferedInputStream(is); File output = new File(FileUtils.getTempDir(), fileName); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(output)); byte[] buffer = new byte[1024]; int read = bis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = bis.read(buffer); } bos.flush(); bos.close(); bis.close(); ic.filesToImport.add(output); filesToDrop.add(output); } } } zf.close(); } catch (ZipException zEx) { System.out.println( "Le fichier " + ret.get(i).getName() + " n'est pas une archive ZIP valide."); } catch (IOException ioEx) { ioEx.printStackTrace(); } finally { if (zf != null) { try { zf.close(); } catch (Throwable t) { } } } } } else if (ret.get(i).getName().toLowerCase().endsWith(".gz")) { try { String fileName = ret.get(i).getName(); fileName = fileName.substring(0, fileName.length() - 3); File output = new File(FileUtils.getTempDir(), fileName); GZIPInputStream gis = new GZIPInputStream(new FileInputStream(ret.get(i))); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); byte[] buffer = new byte[1024]; int read = gis.read(buffer); while (read > 0) { bos.write(buffer, 0, read); read = gis.read(buffer); } bos.flush(); bos.close(); gis.close(); ic.filesToImport.add(output); filesToDrop.add(output); } catch (IOException ioEx) { // nothing to do } } else { ic.filesToImport.add(ret.get(i)); // dans ce cas l, on ne le supprime pas } } return ic; }
From source file:com.drive.student.xutils.http.callback.FileDownloadHandler.java
public File handleEntity(HttpEntity entity, com.drive.student.xutils.http.callback.RequestCallBackHandler callBackHandler, String target, boolean isResume, String responseFileName) throws IOException { if (entity == null || TextUtils.isEmpty(target)) { return null; }// w w w . j a va 2 s. c om File targetFile = new File(target); if (!targetFile.exists()) { File dir = targetFile.getParentFile(); if (dir.exists() || dir.mkdirs()) { targetFile.createNewFile(); } } long current = 0; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { FileOutputStream fileOutputStream = null; if (isResume) { current = targetFile.length(); fileOutputStream = new FileOutputStream(target, true); } else { fileOutputStream = new FileOutputStream(target); } long total = entity.getContentLength() + current; bis = new BufferedInputStream(entity.getContent()); bos = new BufferedOutputStream(fileOutputStream); if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) { return targetFile; } byte[] tmp = new byte[4096]; int len; while ((len = bis.read(tmp)) != -1) { bos.write(tmp, 0, len); current += len; if (callBackHandler != null) { if (!callBackHandler.updateProgress(total, current, false)) { return targetFile; } } } bos.flush(); if (callBackHandler != null) { callBackHandler.updateProgress(total, current, true); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); } if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) { File newFile = new File(targetFile.getParent(), responseFileName); while (newFile.exists()) { newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName); } return targetFile.renameTo(newFile) ? newFile : targetFile; } else { return targetFile; } }
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileUtilities.java
public void decompressZip(File inputZipPath, File zipPath) { int BUFFER = 2048; List<File> zipFiles = new ArrayList<File>(); try {/*from ww w. j a v a2s .co m*/ zipPath.mkdir(); } catch (SecurityException e) { jlog.fatal("Security exception when creating " + zipPath.getName()); } ZipFile zipFile = null; boolean isZip = true; // Open Zip file for reading (should be in temppath) try { zipFile = new ZipFile(inputZipPath, ZipFile.OPEN_READ); } catch (IOException e) { jlog.fatal("IO exception in " + inputZipPath.getName()); } // Create an enumeration of the entries in the zip file Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); if (isZip) { // Process each entry while (zipFileEntries.hasMoreElements()) { // Get a zip file entry ZipEntry entry = zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = null; // destFile should be pointing to temppath\%date%\ try { destFile = new File(zipPath.getAbsolutePath(), currentEntry); destFile = new File(zipPath.getAbsolutePath(), destFile.getName()); } catch (NullPointerException e) { jlog.fatal("File not found" + destFile.getName()); } // If the entry is a .zip add it to the list so that it can be extracted if (currentEntry.endsWith(".zip")) { zipFiles.add(destFile); } try { // Extract file if not a directory if (!entry.isDirectory()) { // Stream the zip entry BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int currentByte; // establish buffer for writing file byte data[] = new byte[BUFFER]; FileOutputStream fos = null; // Write the current file to disk try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { jlog.fatal("File not found " + destFile.getName()); } catch (SecurityException e) { jlog.fatal("Access denied to " + destFile.getName()); } 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(); } } catch (IOException ioe) { jlog.fatal("IO exception in " + zipFile.getName()); } } try { zipFile.close(); } catch (IOException e) { jlog.fatal("IO exception when closing " + zipFile.getName()); } } // Recursively decompress the list of zip files for (File f : zipFiles) { decompressZip(f, zipPath); } return; }
From source file:com.globalsight.everest.tda.TdaHelper.java
public void leverageTDA(TDATM tda, File needLeverageXliffFile, String storePath, String fileName, String sourceLocal, String targetLocal) { int timeoutConnection = 15000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); if (tda.getHostName().indexOf("http://") < 0) { loginUrl = "http://" + tda.getHostName(); } else {/*from ww w . j a v a2 s . c o m*/ loginUrl = tda.getHostName(); } if (tda.getHostName().lastIndexOf("/") < (tda.getHostName().length() - 1)) { loginUrl = loginUrl + "/"; } try { // Judge if the TDA server has the source and target language HttpGet lanGet = new HttpGet(loginUrl + "lang/" + sourceLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes = httpclient.execute(lanGet); StatusLine stl = lanRes.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, sourceLocal.toString()); return; } lanGet.abort(); HttpGet lanGet2 = new HttpGet(loginUrl + "lang/" + targetLocal.toLowerCase() + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse lanRes2 = httpclient.execute(lanGet2); stl = lanRes2.getStatusLine(); if (stl.getStatusCode() != 200) { loggerTDAInfo(stl, targetLocal.toString()); return; } lanGet2.abort(); HttpPost httpPost = new HttpPost(loginUrl + "leverage.json?action=create"); FileBody fileBody = new FileBody(needLeverageXliffFile); StringBody nameBody = new StringBody(tda.getUserName()); StringBody passwordBody = new StringBody(tda.getPassword()); StringBody appKeyBody = new StringBody(appKey); StringBody srcBody = new StringBody(sourceLocal.toLowerCase()); StringBody trBody = new StringBody(targetLocal.toLowerCase()); StringBody confirmBody = new StringBody("true"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileBody); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); reqEntity.addPart("source_lang", srcBody); reqEntity.addPart("target_lang", trBody); reqEntity.addPart("confirm", confirmBody); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() != 201) { loggerTDAInfo(stl, null); return; } JSONObject jso = new JSONObject(EntityUtils.toString(entity)); JSONArray lev = jso.getJSONArray("leverage"); httpPost.abort(); if (lev.length() > 0) { JSONObject obj = lev.getJSONObject(0); String states = obj.getString("state"); // waiting the "not ready" state becoming "ready" state Thread.sleep(3 * 1000); int i = 0; if (!states.equals("ready")) { boolean flag = true; while (flag) { if (i > 40) { s_logger.info("Get TDA job status overtime. TDA job id:" + obj.getInt("id")); s_logger.info("TDA leveraging waited time:" + (40 * 3) + " seconds!"); return; } i++; HttpGet httpget = new HttpGet(loginUrl + "leverage/" + obj.getInt("id") + ".json?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { s_logger.info( "Get TDA job status error, please confirm the TDA url is correct or not! TDA job id:" + obj.getInt("id")); return; } entity = response.getEntity(); JSONObject getObj = new JSONObject(EntityUtils.toString(entity)); if (getObj.getJSONObject("leverage").getString("state").equals("ready")) { s_logger.info("TDA leveraging waited time:" + (i * 3) + " seconds!"); flag = false; } else { Thread.sleep(3 * 1000); } httpget.abort(); } } HttpPost httpPost2 = new HttpPost(loginUrl + "leverage/" + obj.getInt("id") + ".json?action=approve&auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); response = httpclient.execute(httpPost2); entity = response.getEntity(); httpPost2.abort(); HttpGet httpGet = new HttpGet(loginUrl + "leverage/" + obj.getString("id") + "/result.xlf.zip?auth_username=" + tda.getUserName() + "&auth_password=" + tda.getPassword() + "&auth_app_key=" + appKey); HttpResponse response2 = httpclient.execute(httpGet); entity = response2.getEntity(); ZipInputStream fs = new ZipInputStream(entity.getContent()); int BUFFER = 2048; byte data[] = new byte[BUFFER]; int count; while (fs.getNextEntry() != null) { FileOutputStream fos = new FileOutputStream(storePath + File.separator + fileName); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = fs.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } httpGet.abort(); s_logger.info("Leverage TDA TM success, TDA id:" + obj.getString("id")); } } catch (Exception e) { s_logger.error("TDA leverage process error:" + e.getMessage()); } }
From source file:com.live.aac_jenius.globalgroupmute.utilities.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Updater. * * @param file the location of the file to extract. *///from ww w . j a v a2 s . c om private void unzip(String file) { final File fSourceZip = new File(file); try { final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); this.fileIOOrError(destinationFilePath.getParentFile(), destinationFilePath.getParentFile().mkdirs(), true); if (!entry.isDirectory()) { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte[] buffer = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginExists(name)) { File output = new File(updateFolder, name); this.fileIOOrError(output, destinationFilePath.renameTo(output), true); } } } zipFile.close(); // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. moveNewZipFiles(zipPath); } catch (final IOException ex) { this.sender.sendMessage( this.prefix + "The auto-updater tried to unzip a new update file, but was unsuccessful."); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; this.plugin.getLogger().log(Level.SEVERE, null, ex); } finally { this.fileIOOrError(fSourceZip, fSourceZip.delete(), false); } }