/** * Perform the specified SSH file download. * * @param from source remote file URI ({@code ssh} protocol) * @param to target local folder URI ({@code file} protocol) */ private static void download(URI from, URI to) { File out = new File(new File(to), getName(from.getPath())); try (SessionHolder<ChannelSftp> session = new SessionHolder<>(ChannelType.SFTP, from); OutputStream os = new FileOutputStream(out); BufferedOutputStream bos = new BufferedOutputStream(os)) { LOG.info("Downloading {} --> {}", session.getMaskedUri(), to); ChannelSftp channel = session.getChannel(); channel.connect(); channel.cd(getFullPath(from.getPath())); channel.get(getName(from.getPath()), bos); } catch (Exception e) { throw new RemoteFileDownloadFailedException("Cannot download file", e); } }
void openLog(final String loggingFolder) { try { filename = loggingFolder + "/ProcessingTime_" + filterClassName + DATE_FORMAT.format(new Date()) + ".txt"; logStream = new PrintStream(new BufferedOutputStream( new FileOutputStream(new File(filename)))); log.log(Level.INFO, "Created motion flow logging file with " + "processing time statistics at {0}", filename); logStream.println("Processing time statistics of motion flow " + "calculation, averaged over event packets."); logStream.println("Date: " + new Date()); logStream.println("Filter used: " + filterClassName); logStream.println(); logStream.println("timestamp [us] | processing time [us]"); } catch (FileNotFoundException ex) { log.log(Level.SEVERE, null, ex); } }
/** * 从FTP服务器下载指定的文件至本地 * * @author gaoxianglong */ public boolean downloadFile(File file) { boolean result = false; FTPClient ftpClient = ftpConnManager.getFTPClient(); if (null == ftpClient || !ftpClient.isConnected()) { return result; } try (BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(System.getProperty("user.home") + "/" + file.getName()))) { result = ftpClient.retrieveFile(file.getName(), out); if (result) { result = true; log.info("file-->" + file.getPath() + "成功从FTP服务器下载"); } } catch (Exception e) { log.error("error", e); } finally { disconnect(ftpClient); } return result; }
public boolean save(String imageUri, Bitmap bitmap) throws IOException { boolean z = false; Editor editor = this.cache.edit(getKey(imageUri)); if (editor != null) { OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), this.bufferSize); z = false; try { z = bitmap.compress(this.compressFormat, this.compressQuality, os); if (z) { editor.commit(); } else { editor.abort(); } } finally { IoUtils.closeSilently(os); } } return z; }
/** * Starts the WebSocket connection * * @throws IOException */ private void startConnection() throws IOException { bos = new BufferedOutputStream(socket.getOutputStream(), 65536); byte[] key = new byte[16]; Random random = new Random(); random.nextBytes(key); String base64Key = Base64.encodeBase64String(key); byte[] handshake = createHandshake(base64Key); bos.write(handshake); bos.flush(); InputStream inputStream = socket.getInputStream(); verifyServerHandshake(inputStream, base64Key); writerThread.start(); notifyOnOpen(); bis = new BufferedInputStream(socket.getInputStream(), 65536); read(); }
private ZipOutputStream openJarOutputStream(File outputJar) { try { ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outputJar), BUFFER_SIZE)); outputStream.setLevel(0); return outputStream; } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } }
private void downloadZip(String link) throws MalformedURLException, IOException { URL url = new URL(link); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); long max = conn.getContentLength(); gui.setOutputText("Downloding file..."); BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip"))); byte[] buffer = new byte[32 * 1024]; int bytesRead = 0; int in = 0; while ((bytesRead = is.read(buffer)) != -1) { in += bytesRead; fOut.write(buffer, 0, bytesRead); } fOut.flush(); fOut.close(); is.close(); gui.setOutputText("Download Complete!"); }
/** * serialize the datatree and session into the file snapshot * @param dt the datatree to be serialized * @param sessions the sessions to be serialized * @param snapShot the file to store snapshot into */ public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot) throws IOException { if (!close) { OutputStream sessOS = new BufferedOutputStream(new FileOutputStream(snapShot)); CheckedOutputStream crcOut = new CheckedOutputStream(sessOS, new Adler32()); //CheckedOutputStream cout = new CheckedOutputStream() OutputArchive oa = BinaryOutputArchive.getArchive(crcOut); FileHeader header = new FileHeader(SNAP_MAGIC, VERSION, dbId); serialize(dt,sessions,oa, header); long val = crcOut.getChecksum().getValue(); oa.writeLong(val, "val"); oa.writeString("/", "path"); sessOS.flush(); crcOut.close(); sessOS.close(); } }
private void serialize(T newValue) { try { if (!cacheFile.isFile()) { cacheFile.createNewFile(); } chmod.chmod(cacheFile.getParentFile(), 0700); // read-write-execute for user only chmod.chmod(cacheFile, 0600); // read-write for user only OutputStreamBackedEncoder encoder = new OutputStreamBackedEncoder(new BufferedOutputStream(new FileOutputStream(cacheFile))); try { serializer.write(encoder, newValue); } finally { encoder.close(); } } catch (Exception e) { throw new GradleException(String.format("Could not write cache value to '%s'.", cacheFile), e); } }
/** * Constructs a new file logger from the given annotated formula. * * @ensures this.formula' = annotated.node * @ensures this.originalFormula' = annotated.source[annotated.node] * @ensures this.bounds' = bounds * @ensures this.log().roots() = Nodes.conjuncts(annotated) * @ensures no this.records' */ FileLogger(final AnnotatedNode<Formula> annotated, Bounds bounds) { this.annotated = annotated; try { this.file = File.createTempFile("kodkod", ".log"); this.out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file))); } catch (IOException e1) { throw new RuntimeException(e1); } final Map<Formula,Set<Variable>> freeVarMap = freeVars(annotated); final Variable[] empty = new Variable[0]; this.logMap = new FixedMap<Formula,Variable[]>(freeVarMap.keySet()); for (Map.Entry<Formula,Variable[]> e : logMap.entrySet()) { Set<Variable> vars = freeVarMap.get(e.getKey()); int size = vars.size(); if (size == 0) { e.setValue(empty); } else { e.setValue(Containers.identitySort(vars.toArray(new Variable[size]))); } } this.bounds = bounds.unmodifiableView(); }
@Override public boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException { File imageFile = getFile(imageUri); File tmpFile = new File(imageFile.getAbsolutePath() + TEMP_IMAGE_POSTFIX); boolean loaded = false; try { OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile), bufferSize); try { loaded = IoUtils.copyStream(imageStream, os, listener, bufferSize); } finally { IoUtils.closeSilently(os); } } finally { if (loaded && !tmpFile.renameTo(imageFile)) { loaded = false; } if (!loaded) { tmpFile.delete(); } } return loaded; }
/** * @see Channels#newOutputStream(java.nio.channels.WritableByteChannel) */ public OutputStream getContentOutputStream() throws ContentIOException { try { WritableByteChannel channel = getWritableChannel(); OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel)); // done return is; } catch (Throwable e) { throw new ContentIOException("Failed to open stream onto channel: \n" + " writer: " + this, e); } }
public boolean save(String imageUri, InputStream imageStream, CopyListener listener) throws IOException { boolean z = false; Editor editor = this.cache.edit(getKey(imageUri)); if (editor != null) { OutputStream os = new BufferedOutputStream(editor.newOutputStream(0), this.bufferSize); z = false; try { z = IoUtils.copyStream(imageStream, os, listener, this.bufferSize); } finally { IoUtils.closeSilently(os); if (z) { editor.commit(); } else { editor.abort(); } } } return z; }
/** * Write all taken data to a csv file at the desired place. * @param outFile output file that should be used to store data */ public void writeMeasurementDataToFile(final File outFile){ try( final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile)) ){ //print head row for data outputStream.write(csvifyStringList(generateHeadForCsv()).getBytes()); outputStream.flush(); //print actual collected data for(Measurement mt: this.data){ outputStream.write(csvifyStringList(mt.getStringListFromMeasurement()).getBytes()); outputStream.flush(); } } catch (IOException e) { log.log(Level.WARNING,"IO Exception writing measurement data to disc",e); } }
public static void main(String[] args) throws IOException { // Handle command line arguments if (args.length != 2) { System.err.println("Usage: java AdaptiveHuffmanCompress InputFile OutputFile"); System.exit(1); return; } File inputFile = new File(args[0]); File outputFile = new File(args[1]); // Perform file compression InputStream in = new BufferedInputStream(new FileInputStream(inputFile)); BitOutputStream out = new BitOutputStream(new BufferedOutputStream(new FileOutputStream(outputFile))); try { compress(in, out); } finally { out.close(); in.close(); } }
private void prepare(File bundleFile, File exploderDir, boolean hasInnerJar) { getLogger().info("prepare bundle " + bundleFile.getAbsolutePath()); if (exploderDir.exists()) { return; } LibraryCache.unzipAar(bundleFile, exploderDir, getProject()); if (hasInnerJar) { // verify the we have a classes.jar, if we don't just create an empty one. File classesJar = new File(new File(exploderDir, "jars"), "classes.jar"); if (classesJar.exists()) { return; } try { Files.createParentDirs(classesJar); JarOutputStream jarOutputStream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream( classesJar)), new Manifest()); jarOutputStream.close(); } catch (IOException e) { throw new RuntimeException("Cannot create missing classes.jar", e); } } }
/** * serialize the datatree and session into the file snapshot * @param dt the datatree to be serialized * @param sessions the sessions to be serialized * @param snapShot the file to store snapshot into * @param fsync sync the file immediately after write */ public synchronized void serialize(DataTree dt, Map<Long, Integer> sessions, File snapShot, boolean fsync) throws IOException { if (!close) { try (CheckedOutputStream crcOut = new CheckedOutputStream(new BufferedOutputStream(fsync ? new AtomicFileOutputStream(snapShot) : new FileOutputStream(snapShot)), new Adler32())) { //CheckedOutputStream cout = new CheckedOutputStream() OutputArchive oa = BinaryOutputArchive.getArchive(crcOut); FileHeader header = new FileHeader(SNAP_MAGIC, VERSION, dbId); serialize(dt, sessions, oa, header); long val = crcOut.getChecksum().getValue(); oa.writeLong(val, "val"); oa.writeString("/", "path"); crcOut.flush(); } } }
public static void copyFiles( File sourceDir, File destDir, String... resourceNames ) throws IOException { for( String resourceName : resourceNames ) { File src = new File( sourceDir, resourceName ); if ( !src.canRead() ) { TestCase.fail( "The test requires the file: " + resourceName + " to be readable and stored in: " + sourceDir ); } InputStream is = new FileInputStream( src ); BufferedInputStream bis = new BufferedInputStream( is ); File dest = new File( destDir, resourceName ); File parent = dest.getParentFile(); if ( !parent.exists() ) { parent.mkdirs(); } dest.createNewFile(); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( dest ) ); copyFile( bis, bos ); } }
public static void unzip( ZipFile zip, File dest ) throws IOException { for( Enumeration<? extends ZipEntry> e = zip.entries(); e.hasMoreElements(); ) { ZipEntry entry = e.nextElement(); File f = new File( dest, entry.getName() ); if ( entry.isDirectory() ) { f.mkdirs(); } else { f.getParentFile().mkdirs(); f.createNewFile(); BufferedInputStream bis = new BufferedInputStream( zip.getInputStream( entry ) ); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( f ) ); copyFile( bis, bos ); } } }
@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 ); }
public static void copyFile(File sourceFile, File targetFile) throws IOException { // 新建文件输入流并对它进行缓冲 FileInputStream input = new FileInputStream(sourceFile); BufferedInputStream inBuff = new BufferedInputStream(input); // 新建文件输出流并对它进行缓冲 FileOutputStream output = new FileOutputStream(targetFile); BufferedOutputStream outBuff = new BufferedOutputStream(output); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // 刷新此缓冲的输出流 outBuff.flush(); //关闭流 inBuff.close(); outBuff.close(); output.close(); input.close(); }
@Override public StoredScript store(final String functionKey, final Source source, final StoredScript script) { if (readOnly || script == null || belowThreshold(source)) { return null; } final File file = getCacheFile(source, functionKey); try { return AccessController.doPrivileged(new PrivilegedExceptionAction<StoredScript>() { @Override public StoredScript run() throws IOException { try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) { out.writeObject(script); } getLogger().info("stored ", source, "-", functionKey); return script; } }); } catch (final PrivilegedActionException e) { getLogger().warning("failed to store ", script, "-", functionKey, ": ", e.getException()); return null; } }
/** * save image from uri * @param outPath * @param bitmap * @return */ public static String saveBitmapToLocal(String outPath , Bitmap bitmap) { try { String imagePath = outPath + HelpUtils.md5(DateFormat.format("yyyy-MM-dd-HH-mm-ss", System.currentTimeMillis()).toString()) + ".jpg"; File file = new File(imagePath); if(!file.exists()) { file.createNewFile(); } BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.PNG, 100, bufferedOutputStream); bufferedOutputStream.close(); LogUtil.d(TAG, "photo image from data, path:" + imagePath); return imagePath; } catch (Exception e) { e.printStackTrace(); } return null; }
public Packer(final File destFile, final Signer signer, final Boolean inPlace) throws FileNotFoundException { this.inPlace = inPlace; if (inPlace) { //In codesign.py this is what we use this.zipStream = new ZipOutputStream( new DataOutputStream( new ByteArrayOutputStream(128*1024*1024-1))); //Avoid java bug https://bugs.openjdk.java.net/browse/JDK-8055949 by being able to get to max buffer size of MAX_INT-16 zipStream.setLevel(Deflater.NO_COMPRESSION); } else { this.zipStream = new ZipOutputStream( new BufferedOutputStream( new FileOutputStream(destFile))); } this.signer = signer; }
private void copyFiles(File sourceDir, File destDir, String[] resourceNames) throws IOException { for( String resourceName : resourceNames ) { File src = new File( sourceDir, resourceName ); if ( !src.canRead() ) { TestCase.fail( "The test requires the file: " + resourceName + " to be readable and stored in: " + sourceDir ); } InputStream is = new FileInputStream( src ); BufferedInputStream bis = new BufferedInputStream( is ); //Strip last folder to align with packagename File dest = new File( destDir, resourceName.replace(testDataExtension(), DATA_EXTENSION) ); File parent = dest.getParentFile(); if ( !parent.exists() ) { parent.mkdirs(); } dest.createNewFile(); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream( dest ) ); copyFile( bis, bos ); } }
private void createBlobFile(int size) throws Exception { if (testBlobFile != null && testBlobFile.length() != size) { testBlobFile.delete(); } testBlobFile = File.createTempFile(TEST_BLOB_FILE_PREFIX, ".dat"); testBlobFile.deleteOnExit(); // TODO: following cleanup doesn't work correctly during concurrent execution of testsuite // cleanupTempFiles(testBlobFile, TEST_BLOB_FILE_PREFIX); BufferedOutputStream bOut = new BufferedOutputStream(new FileOutputStream(testBlobFile)); int dataRange = Byte.MAX_VALUE - Byte.MIN_VALUE; for (int i = 0; i < size; i++) { bOut.write((byte) ((Math.random() * dataRange) + Byte.MIN_VALUE)); } bOut.flush(); bOut.close(); }
protected void writeRenameReadCompare(Path path, long len) throws IOException, NoSuchAlgorithmException { // If len > fs.s3n.multipart.uploads.block.size, // we'll use a multipart upload copy MessageDigest digest = MessageDigest.getInstance("MD5"); OutputStream out = new BufferedOutputStream( new DigestOutputStream(fs.create(path, false), digest)); for (long i = 0; i < len; i++) { out.write('Q'); } out.flush(); out.close(); assertTrue("Exists", fs.exists(path)); // Depending on if this file is over 5 GB or not, // rename will cause a multipart upload copy Path copyPath = path.suffix(".copy"); fs.rename(path, copyPath); assertTrue("Copy exists", fs.exists(copyPath)); // Download file from S3 and compare the digest against the original MessageDigest digest2 = MessageDigest.getInstance("MD5"); InputStream in = new BufferedInputStream( new DigestInputStream(fs.open(copyPath), digest2)); long copyLen = 0; while (in.read() != -1) {copyLen++;} in.close(); assertEquals("Copy length matches original", len, copyLen); assertArrayEquals("Digests match", digest.digest(), digest2.digest()); }
private static BufferedOutputStream createOutputStream(File file) throws IOException { int retry = 0; while (true) { try { return new BufferedOutputStream(new FileOutputStream(file)); } catch (IOException ex) { retry++; if (retry > 7) { throw ex; } try { Thread.sleep(retry * 34); } catch (InterruptedException iex) { throw ex; } } } }
/** * Saves a Bitmap object to disk for analysis. * * @param bitmap The bitmap to save. */ public static void saveBitmap(final Bitmap bitmap) { final File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "tensorflow_preview.png"); Log.d("ImageHelper", String.format("Saving %dx%d bitmap to %s.", bitmap.getWidth(), bitmap.getHeight(), file.getAbsolutePath())); if (file.exists()) { file.delete(); } try (FileOutputStream fs = new FileOutputStream(file); BufferedOutputStream out = new BufferedOutputStream(fs)) { bitmap.compress(Bitmap.CompressFormat.PNG, 99, out); } catch (final Exception e) { Log.w("ImageHelper", "Could not save image for debugging. " + e.getMessage()); } }
@RequestMapping(value = "/email/attachment/{id}",method = RequestMethod.GET) public void getAttachmentContent(@PathVariable("id") Long id, HttpServletResponse response) { final AttachmentEntity attachment = attachmentService.findAttachmentById(id); if (attachment != null) { try { ServletOutputStream stream = response.getOutputStream(); OutputStream out = new BufferedOutputStream(stream); response.resetBuffer(); response.setBufferSize(attachment.getAttachmentContent().getData().length); response.setHeader("Content-Length", String.valueOf(attachment. getAttachmentContent().getData().length)); out.write(attachment.getAttachmentContent().getData()); out.close(); stream.close(); } catch (final IOException e) { log.error("Unable to open file", e); } } else { log.error("File does not exist"); } }
@Test public void testEmptyFinalColumn() throws Exception { String dfs_temp = getDfsTestTmpSchemaLocation(); File table_dir = new File(dfs_temp, "emptyFinalColumn"); table_dir.mkdir(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.csvh"))); os.write("field1,field2\n".getBytes()); for (int i = 0; i < 10000; i++) { os.write("a,\n".getBytes()); } os.flush(); os.close(); String query = "select * from dfs_test.emptyFinalColumn"; TestBuilder builder = testBuilder() .sqlQuery(query) .ordered() .baselineColumns("field1", "field2"); for (int i = 0; i < 10000; i++) { builder.baselineValues("a", ""); } builder.go(); }
@Override protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws IOException { String callbackUrl = (String) req.getSession().getAttribute("callbackUrl"); if(callbackUrl == null) { BufferedOutputStream bos = new BufferedOutputStream(resp.getOutputStream()); PrintWriter pw = new PrintWriter(bos); resp.setContentType("application/json"); resp.setHeader("access-control-allow-origin", "*"); pw.print(String.format( "{\"error\": {\"code\": \"%s\", \"errorMessage\": \"%s\", \"errorDescription\": \"%s\", \"errorUri\": \"%s\", \"state\": \"%s\"}}", errorResponse.getCode(), errorResponse.getError(), errorResponse.getErrorDescription(), errorResponse.getErrorUri(), errorResponse.getState() )); pw.close(); } else { resp.sendRedirect(callbackUrl + "?notLoggedIn=true"); req.getSession().removeAttribute("callbackUrl"); } }
public static String serializeBundle(final Bundle bundle) { String base64; final Parcel parcel = Parcel.obtain(); try { parcel.writeBundle(bundle); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final GZIPOutputStream zos = new GZIPOutputStream(new BufferedOutputStream(bos)); zos.write(parcel.marshall()); zos.close(); base64 = Base64.encodeToString(bos.toByteArray(), 0); } catch (IOException e) { e.printStackTrace(); base64 = null; } finally { parcel.recycle(); } return base64; }
public void writeIndexJar() throws IOException, XmlPullParserException, LocalRepoKeyStore.InitException { BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(xmlIndexJarUnsigned)); JarOutputStream jo = new JarOutputStream(bo); JarEntry je = new JarEntry("index.xml"); jo.putNextEntry(je); new IndexXmlBuilder().build(context, apps, jo); jo.close(); bo.close(); try { LocalRepoKeyStore.get(context).signZip(xmlIndexJarUnsigned, xmlIndexJar); } catch (LocalRepoKeyStore.InitException e) { throw new IOException("Could not sign index - keystore failed to initialize"); } finally { attemptToDelete(xmlIndexJarUnsigned); } }
/** * Function to copy database from assets to internal memory */ public static void copyDatabase(Context context) { try { File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + context.getString(R.string.app_folder_path) + "/quran.sqlite"); if (!file.exists()) { InputStream inputStream = context.getApplicationContext().getAssets().open("quran.sqlite"); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file)); int length = 0; while ((length = inputStream.read()) > -1) { outputStream.write(length); } outputStream.flush(); outputStream.close(); inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } }
public String savePicture(Bitmap bitmap, String tag) { String strCaptureFilePath = PATH + tag + "_VIN_" + pictureName() + ".jpg"; File dir = new File(PATH); if (!dir.exists()) { dir.mkdirs(); } File file = new File(strCaptureFilePath); if (file.exists()) { file.delete(); } try { file.createNewFile(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); } catch (IOException e) { showToast("图像存储失败"); } return strCaptureFilePath; }
static File unzipIntoTempDirectory(File file) throws IOException { final int random = new SecureRandom().nextInt(); final File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "tmpdcd" + random); // on ajoute random au répertoire temporaire pour l'utilisation d'instances en parallèle if (!tmpDirectory.exists() && !tmpDirectory.mkdirs()) { throw new IOException(tmpDirectory + " can't be created"); } final ZipFile zipFile = new ZipFile(file); try { final byte[] buffer = new byte[64 * 1024]; // buffer de 64 Ko pour la décompression final Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements() && !Thread.currentThread().isInterrupted()) { final ZipEntry zipEntry = entries.nextElement(); final boolean toBeCopied = zipEntry.getName().endsWith(".class") || isViewFile(zipEntry.getName()); if (toBeCopied && !zipEntry.isDirectory()) { final File tmpFile = new File(tmpDirectory, zipEntry.getName()); if (!tmpFile.getParentFile().exists() && !tmpFile.getParentFile().mkdirs()) { throw new IOException(tmpFile.getParentFile() + " can't be created"); } final InputStream input = zipFile.getInputStream(zipEntry); final OutputStream output = new BufferedOutputStream( new FileOutputStream(tmpFile), (int) zipEntry.getSize()); try { copy(buffer, input, output); } finally { input.close(); output.close(); } } } } finally { zipFile.close(); } return tmpDirectory; }
@TaskAction public void generate() { Properties properties = new Properties(); if (!getPluginClasspath().isEmpty()) { List<String> paths = CollectionUtils.collect(getPluginClasspath(), new Transformer<String, File>() { @Override public String transform(File file) { return file.getAbsolutePath().replaceAll("\\\\", "/"); } }); StringBuilder implementationClasspath = new StringBuilder(); Joiner.on(File.pathSeparator).appendTo(implementationClasspath, paths); properties.setProperty(IMPLEMENTATION_CLASSPATH_PROP_KEY, implementationClasspath.toString()); // As these files are inputs into this task, they have just been snapshotted by the task up-to-date checking. // We should be reusing those persistent snapshots to avoid reading into memory again. HashClassPathSnapshotter classPathSnapshotter = new HashClassPathSnapshotter(new DefaultFileHasher()); String hash = classPathSnapshotter.snapshot(new DefaultClassPath(getPluginClasspath())).getStrongHash().toString(); properties.setProperty(IMPLEMENTATION_CLASSPATH_HASH_PROP_KEY, hash); } File outputFile = new File(getOutputDirectory(), METADATA_FILE_NAME); try { OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); GUtil.savePropertiesNoDateComment(properties, outputStream); } catch (IOException e) { throw new UncheckedIOException(e); } }
private void writeRequestFile(HttpURLConnection connection, String path) throws IOException { // Use MediaUtil.openMedia to open the file. This means that path could be file on the SD card, // an asset, a contact picture, etc. BufferedInputStream in = new BufferedInputStream(MediaUtil.openMedia(form, path)); try { // Write the file's data. // According to the documentation at // http://developer.android.com/reference/java/net/HttpURLConnection.html // HttpURLConnection uses the GET method by default. It will use POST if setDoOutput(true) has // been called. connection.setDoOutput(true); // This makes it something other than a HTTP GET. connection.setChunkedStreamingMode(0); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); try { while (true) { int b = in.read(); if (b == -1) { break; } out.write(b); } out.flush(); } finally { out.close(); } } finally { in.close(); } }