Java Code Examples for java.io.BufferedOutputStream

The following are top voted examples for showing how to use java.io.BufferedOutputStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Remote-Session   File: SshUtils.java   Source Code and License 10 votes vote down vote up
/**
 * 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);
    }
}
 
Example 2
Project: Reer   File: RuntimeShadedJarCreator.java   Source Code and License 7 votes vote down vote up
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);
    }
}
 
Example 3
Project: TITAN   File: FtpUtils.java   Source Code and License 7 votes vote down vote up
/**
 * 从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;
}
 
Example 4
Project: letv   File: LruDiscCache.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 5
Project: jaer   File: MotionFlowStatistics.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 6
Project: java-android-websocket-client   File: WebSocketClient.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 7
Project: ObsidianSuite   File: Downloader.java   Source Code and License 6 votes vote down vote up
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!");

}
 
Example 8
Project: fuck_zookeeper   File: FileSnap.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 9
Project: Reer   File: SimpleStateCache.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 10
Project: org.alloytools.alloy   File: FileLogger.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 11
Project: ZooKeeper   File: FileSnap.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 12
Project: GitHub   File: BaseDiskCache.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 13
Project: alfresco-repository   File: AbstractContentWriter.java   Source Code and License 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example 14
Project: letv   File: LruDiscCache.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 15
Project: Byter   File: PerformanceTimer.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Project: SparkSeq   File: AdaptiveHuffmanCompress.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 17
Project: atlas   File: PrepareAwoBundleTask.java   Source Code and License 6 votes vote down vote up
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);
        }
    }
}
 
Example 18
Project: https-github.com-apache-zookeeper   File: FileSnap.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 19
Project: incubator-netbeans   File: TestUtil.java   Source Code and License 6 votes vote down vote up
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 );
        }
    }
 
Example 20
Project: incubator-netbeans   File: TestUtil.java   Source Code and License 6 votes vote down vote up
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 );
        }
    }
    
}
 
Example 21
Project: dataplatform-config   File: GeneralConfMaker.java   Source Code and License 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 22
Project: ESPD   File: FileOperations.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 23
Project: OpenJSharp   File: CodeStore.java   Source Code and License 6 votes vote down vote up
@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;
    }
}
 
Example 24
Project: youkes_browser   File: HelpUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: ipack   File: Packer.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 26
Project: incubator-netbeans   File: HintsTestBase.java   Source Code and License 6 votes vote down vote up
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 );
    }
}
 
Example 27
Project: OpenVertretung   File: BlobTest.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 28
Project: hadoop   File: TestJets3tNativeFileSystemStore.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 29
Project: OperatieBRP   File: AfnemerindicatieConversie.java   Source Code and License 6 votes vote down vote up
private void converteerHisPersafnemerindicatieTabel(final long maxAfnemerindicatieId)
        throws IOException {
    afnemerindicatieDatabaseInteractieStrategy.dumpHisAfnemerindicatieTabel(hisPersafnemerindicatieOudFile);
    final long maxHisAfnemerindicatieId = bepaalMaxId(PersoonAfnemerindicatieHistorie.class).longValue();
    try (OutputStream os = new BufferedOutputStream(new FileOutputStream(hisPersafnemerindicatieNieuwFile))) {
        try (InputStream is = new BufferedInputStream(new FileInputStream(hisPersafnemerindicatieOudFile))) {
            final LineIterator it = IOUtils.lineIterator(is, StandardCharsets.UTF_8);
            converteerHisAfnemerindicatiebestand(maxAfnemerindicatieId, maxHisAfnemerindicatieId, os, it);
        }
    }
    afnemerindicatieDatabaseInteractieStrategy.vulHisAfnemerindicatieTabel(hisPersafnemerindicatieNieuwFile);
}
 
Example 30
Project: incubator-netbeans   File: FileUtils.java   Source Code and License 6 votes vote down vote up
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;
            }
        }
    }       
}
 
Example 31
Project: androidthings-imageclassifier   File: Helper.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 32
Project: maildump   File: EmailController.java   Source Code and License 6 votes vote down vote up
@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");
	}
}
 
Example 33
Project: dremio-oss   File: TestCsvHeader.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 34
Project: agendamlgr   File: OAuthCallbackServlet.java   Source Code and License 6 votes vote down vote up
@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");
    }
}
 
Example 35
Project: Phoenix-for-VK   File: BundleUtil.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 36
Project: mobile-store   File: LocalRepoManager.java   Source Code and License 6 votes vote down vote up
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);
    }

}
 
Example 37
Project: QuranAndroid   File: FileManager.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 38
Project: CXJPadProject   File: OrcVinActivity.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 39
Project: dead-code-detector   File: DcdHelper.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 40
Project: Reer   File: PluginUnderTestMetadata.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 41
Project: appinventor-extensions   File: Web.java   Source Code and License 5 votes vote down vote up
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();
  }
}
 
Example 42
Project: Reer   File: WriteProperties.java   Source Code and License 5 votes vote down vote up
@TaskAction
public void writeProperties() throws IOException {
    Charset charset = Charset.forName(getEncoding());
    OutputStream out = new BufferedOutputStream(new FileOutputStream(getOutputFile()));
    try {
        PropertiesUtils.store(getProperties(), out, getComment(), charset, getLineSeparator());
    } finally {
        IOUtils.closeQuietly(out);
    }
}
 
Example 43
Project: exciting-app   File: AnimatedGifEncoder.java   Source Code and License 5 votes vote down vote up
public boolean start(String file) {
    boolean ok = true;
    try {
        out = new BufferedOutputStream(new FileOutputStream(file));
        ok = start(out);
        Log.i("AnimatedGifEncode...", "AnimatedGifEncode is start =" + file);
        closeStream = true;
    } catch (IOException e) {
        ok = false;
    }
    return started = ok;
}
 
Example 44
Project: elasticsearch_my   File: MockTcpTransport.java   Source Code and License 5 votes vote down vote up
@Override
protected void sendMessage(MockChannel mockChannel, BytesReference reference, Runnable sendListener) throws IOException {
    synchronized (mockChannel) {
        final Socket socket = mockChannel.activeChannel;
        OutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
        reference.writeTo(outputStream);
        outputStream.flush();
    }
    if (sendListener != null) {
        sendListener.run();
    }
}
 
Example 45
Project: Byter   File: Generator.java   Source Code and License 5 votes vote down vote up
/**
 * Write given content to file.
 * @param content configuration content eg.
 * @param file file to write data to.
 */
public static void writeToFile(final String content, final File file){
    try(
        final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file))
    ){
        outputStream.write(content.getBytes());
        outputStream.flush();
    } catch (IOException e) {
        log.log(Level.WARNING,"IO Exception during write of a String to a File. Check Stacktrace for issues.",e);
    }
}
 
Example 46
Project: q-mail   File: MigrationTest.java   Source Code and License 5 votes vote down vote up
private void copyAttachmentFromFile(String resourceName, int attachmentId, int expectedFilesize) throws IOException {
    File resourceFile = new File(getClass().getResource("/attach/" + resourceName).getFile());
    File attachmentFile = new File(attachmentDir, Integer.toString(attachmentId));
    BufferedInputStream input = new BufferedInputStream(new FileInputStream(resourceFile));
    BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(attachmentFile));
    int copied = IOUtils.copy(input, output);
    input.close();
    output.close();
    Assert.assertEquals(expectedFilesize, copied);
}
 
Example 47
Project: parabuild-ci   File: HSQLClientConnection.java   Source Code and License 5 votes vote down vote up
protected void openConnection(String host, int port,
                                  boolean isTLS) throws HsqlException {

        try {
            socket = HsqlSocketFactory.getInstance(isTLS).createSocket(host,
                                                   port);
            dataOutput = new BufferedOutputStream(socket.getOutputStream());
            dataInput = new DataInputStream(
                new BufferedInputStream(socket.getInputStream()));
        } catch (Exception e) {

/** @todo fredt - change error to no connetion established */
            throw Trace.error(Trace.SOCKET_ERROR);
        }
    }
 
Example 48
Project: Byter   File: NetworkDataInput.java   Source Code and License 5 votes vote down vote up
@Override
public void sendHeartBeat(final BufferedOutputStream out) {
    try {
        out.write("CONNECTION CHECK".getBytes(Charset.forName("UTF-8")));
    } catch (final SocketException se){
        log.log(Level.FINE, "Cleaning up the socket.");
        finishSocket();
    } catch (final IOException e) {
        log.log(Level.INFO,"IO Exception during HeartBeat. Seems that the Client disconnected.");
    }
}
 
Example 49
Project: GitHub   File: LocalFileFetchProducerTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  MockitoAnnotations.initMocks(this);
  mExecutor = new TestExecutorService(new FakeClock());
  mLocalFileFetchProducer =
      new LocalFileFetchProducer(mExecutor, mPooledByteBufferFactory);
  mFile = new File(RuntimeEnvironment.application.getExternalFilesDir(null), TEST_FILENAME);
  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(mFile));
  bos.write(new byte[INPUT_STREAM_LENGTH], 0 , INPUT_STREAM_LENGTH);
  bos.close();

  mProducerContext = new SettableProducerContext(
      mImageRequest,
      mRequestId,
      mProducerListener,
      mock(Object.class),
      ImageRequest.RequestLevel.FULL_FETCH,
      false,
      true,
      Priority.MEDIUM);
  when(mImageRequest.getSourceFile()).thenReturn(mFile);
  doAnswer(
      new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          mCapturedEncodedImage =
              EncodedImage.cloneOrNull((EncodedImage) invocation.getArguments()[0]);
          return null;
        }
      })
      .when(mConsumer)
      .onNewResult(notNull(EncodedImage.class), anyInt());
}
 
Example 50
Project: aws-sdk-java-v2   File: RandomTempFile.java   Source Code and License 5 votes vote down vote up
public void createFile(long sizeInBytes) throws IOException {
    deleteOnExit();

    try (FileOutputStream outputStream = new FileOutputStream(this);
         BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
         InputStream inputStream = new RandomInputStream(sizeInBytes, binaryData)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) > -1) {
            bufferedOutputStream.write(buffer, 0, bytesRead);
        }
    }
}
 
Example 51
Project: ramus   File: TcpClientConnection.java   Source Code and License 5 votes vote down vote up
public void start() throws UnknownHostException, IOException,
        ClassNotFoundException {
    socket = new Socket(host, port);
    inputStream = new ObjectInputStream(socket.getInputStream());
    System.out.println("Server: " + inputStream.readObject());
    OutputStream stream = new BufferedOutputStream(
            socket.getOutputStream(), 64 * 1024);
    outputStream = new ObjectOutputStream(stream);
    thread.start();
}
 
Example 52
Project: javaide   File: Util.java   Source Code and License 5 votes vote down vote up
/**
 * @source http://stackoverflow.com/a/27050680
 */
public static void unzip(InputStream zipFile, File targetDirectory) throws Exception {
    ZipInputStream in = new ZipInputStream(new BufferedInputStream(zipFile));
    try {
        ZipEntry ze;
        int count;
        byte[] buffer = new byte[8192];
        while ((ze = in.getNextEntry()) != null) {
            File file = new File(targetDirectory, ze.getName());
            File dir = ze.isDirectory() ? file : file.getParentFile();
            if (!dir.isDirectory() && !dir.mkdirs()) {
                throw new Exception("Failed to ensure directory: " + dir.getAbsolutePath());
            }
            if (ze.isDirectory()) {
                continue;
            }
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            try {
                while ((count = in.read(buffer)) != -1)
                    out.write(buffer, 0, count);
            } finally {
                out.close();
            }
            long time = ze.getTime();
            if (time > 0) {
                file.setLastModified(time);
            }
        }
    } finally {
        in.close();
    }
}
 
Example 53
Project: ats-framework   File: LocalFileSystemOperations.java   Source Code and License 5 votes vote down vote up
private void extractTar( String tarFilePath, String outputDirPath ) {

        TarArchiveEntry entry = null;
        try (TarArchiveInputStream tis = new TarArchiveInputStream(new FileInputStream(tarFilePath))) {
            while ( (entry = (TarArchiveEntry) tis.getNextEntry()) != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Extracting " + entry.getName());
                }
                File entryDestination = new File(outputDirPath, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    OutputStream out = new BufferedOutputStream(new FileOutputStream(entryDestination));
                    IoUtils.copyStream(tis, out, false, true);
                }
                if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                    // set file/dir permissions, after it is created
                    Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                                  getPosixFilePermission(entry.getMode()));
                }
            }
        } catch (Exception e) {
            String errorMsg = null;
            if (entry != null) {
                errorMsg = "Unable to untar " + entry.getName() + " from " + tarFilePath
                           + ".Target directory '" + outputDirPath + "' is in inconsistent state.";
            } else {
                errorMsg = "Could not read data from " + tarFilePath;
            }
            throw new FileSystemOperationException(errorMsg, e);
        }

    }
 
Example 54
Project: simple-share-android   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static boolean uncompress(File zipFile) {
    boolean success = false;
    try {
        FileInputStream fis = new FileInputStream(zipFile);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        File destFolder = new File(zipFile.getParent(), FileUtils.getNameFromFilename(zipFile.getName()));
        destFolder.mkdirs();
        while ((entry = zis.getNextEntry()) != null) {
            File dest = new File(destFolder, entry.getName());
            dest.getParentFile().mkdirs();

            if(entry.isDirectory()) {
                if (!dest.exists()) {
                    dest.mkdirs();
                }
            } else {
                int size;
                byte[] buffer = new byte[2048];
                FileOutputStream fos = new FileOutputStream(dest);
                BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
                while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, size);
                }
                bos.flush();
                bos.close();
                IoUtils.flushQuietly(bos);
                IoUtils.closeQuietly(bos);
            }
            zis.closeEntry();
        }
        IoUtils.closeQuietly(zis);
        IoUtils.closeQuietly(fis);
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return success;
}
 
Example 55
Project: cos-java-sdk-v5   File: GeneratePresignedUrlTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPutFile() throws IOException {
    if (!judgeUserInfoValid()) {
        return;
    }
    String key = "ut/generate_url_test_upload.txt";
    File localFile = buildTestFile(1024);
    Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
    URL url = cosclient.generatePresignedUrl(bucket, key, expirationTime, HttpMethodName.PUT);

    System.out.println(url.toString());

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("PUT");

    BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(localFile));
    int readByte = -1;
    while ((readByte = bis.read()) != -1) {
        bos.write(readByte);
    }
    bis.close();
    bos.close();
    int responseCode = connection.getResponseCode();
    assertEquals(200, responseCode);

    headSimpleObject(key, localFile.length(), Md5Utils.md5Hex(localFile));
    clearObject(key);
    localFile.delete();
}
 
Example 56
Project: JavaGraph   File: Unzipper.java   Source Code and License 5 votes vote down vote up
/**
 * Extracts a zip entry (file entry).
 * @param zipIn the input stream containing the entry to be extracted
 * @param filePath the path to the file where the extracted entry should be saved
 * @throws IOException if any error occurred during extraction
 */
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
    try (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);
        }
    }
}
 
Example 57
Project: incubator-netbeans   File: RSSFeed.java   Source Code and License 5 votes vote down vote up
CachingInputStream (InputStream is, String path, String time) 
throws IOException {
    super(is);
    File storage = initCacheStore(path);
    os = new BufferedOutputStream(new FileOutputStream(storage));
    modTime = time;
    this.path = path;
}
 
Example 58
Project: TPlayer   File: FileUtils.java   Source Code and License 5 votes vote down vote up
public static void writeToFile(InputStream dataIns, File target) throws IOException {
    final int BUFFER = 1024;
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
    int count;
    byte data[] = new byte[BUFFER];
    while ((count = dataIns.read(data, 0, BUFFER)) != -1) {
        bos.write(data, 0, count);
    }
    bos.close();
}
 
Example 59
Project: accumulate   File: BinaryOut.java   Source Code and License 5 votes vote down vote up
/**
 * Create a binary output stream from a filename.
 */
public BinaryOut(String s) {
    try {
        OutputStream os = new FileOutputStream(s);
        out = new BufferedOutputStream(os);
    }
    catch (IOException e) { e.printStackTrace(); }
}
 
Example 60
Project: incubator-netbeans   File: TestDataGenerator.java   Source Code and License 5 votes vote down vote up
private void fillWithMagicBytes(File testFile, int index) throws IOException {
  OutputStream out = new BufferedOutputStream(new FileOutputStream(testFile));
  int alreadyWritten = 0;
  while (alreadyWritten < testFileSizes[index]) {
    int writeCount = alreadyWritten + buffer.length <= testFileSizes[index] ? buffer.length : testFileSizes[index] - alreadyWritten;
    out.write(buffer, 0, writeCount);
    alreadyWritten += writeCount;
  }
  out.flush();
  out.close();
}