Java Code Examples for java.io.BufferedOutputStream#write()

The following examples show how to use java.io.BufferedOutputStream#write() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: jdk8u60   File: Font2DTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void writeCurrentOptions( String fileName ) {
    try {
        String curOptions = fp.getCurrentOptions();
        BufferedOutputStream bos =
          new BufferedOutputStream( new FileOutputStream( fileName ));
        /// Prepend title and the option that is only obtainable here
        int range[] = rm.getSelectedRange();
        String completeOptions =
          ( "Font2DTest Option File\n" +
            displayGridCBMI.getState() + "\n" +
            force16ColsCBMI.getState() + "\n" +
            showFontInfoCBMI.getState() + "\n" +
            rm.getSelectedItem() + "\n" +
            range[0] + "\n" + range[1] + "\n" + curOptions + tFileName);
        byte toBeWritten[] = completeOptions.getBytes( "UTF-16" );
        bos.write( toBeWritten, 0, toBeWritten.length );
        bos.close();
    }
    catch ( Exception ex ) {
        fireChangeStatus( "ERROR: Failed to Save Options File; See Stack Trace", true );
        ex.printStackTrace();
    }
}
 
Example 2
private void writeCurrentOptions( String fileName ) {
    try {
        String curOptions = fp.getCurrentOptions();
        BufferedOutputStream bos =
          new BufferedOutputStream( new FileOutputStream( fileName ));
        /// Prepend title and the option that is only obtainable here
        int range[] = rm.getSelectedRange();
        String completeOptions =
          ( "Font2DTest Option File\n" +
            displayGridCBMI.getState() + "\n" +
            force16ColsCBMI.getState() + "\n" +
            showFontInfoCBMI.getState() + "\n" +
            rm.getSelectedItem() + "\n" +
            range[0] + "\n" + range[1] + "\n" + curOptions + tFileName);
        byte toBeWritten[] = completeOptions.getBytes( "UTF-16" );
        bos.write( toBeWritten, 0, toBeWritten.length );
        bos.close();
    }
    catch ( Exception ex ) {
        fireChangeStatus( "ERROR: Failed to Save Options File; See Stack Trace", true );
        ex.printStackTrace();
    }
}
 
Example 3
Source Project: DevUtils   File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 追加文件
 * <pre>
 *     如果未创建文件, 则会创建并写入数据 ( 等同 {@link #saveFile} )
 *     如果已创建文件, 则在结尾追加数据
 * </pre>
 * @param file 文件
 * @param data 待追加数据
 * @return {@code true} success, {@code false} fail
 */
public static boolean appendFile(final File file, final byte[] data) {
    try {
        // 防止文件夹没创建
        createFolder(getDirName(file));
        // 写入文件
        FileOutputStream fos = new FileOutputStream(file, true);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bos.write(data);
        bos.close();
        fos.close();
        return true;
    } catch (Exception e) {
        JCLogUtils.eTag(TAG, e, "appendFile");
    }
    return false;
}
 
Example 4
Source Project: imsdk-android   File: FileHelper.java    License: MIT License 6 votes vote down vote up
public static boolean inputStreamToFile(InputStream inputStream, String filename, String tmpSuffix) throws IOException {

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

        return renameFile(file, filename);
    }
 
Example 5
Source Project: emissary   File: ConfigUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Bring remote config data to the local system if possible
 *
 * @param f config item to work with
 * @param outputPath path and filename to write the config item data onto
 * @throws IOException on read or write problems
 */
public static void getConfigDataLocal(final String f, final String outputPath) throws IOException {
    final InputStream is = getConfigData(f);
    final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(outputPath));
    try {
        final byte[] buf = new byte[4096];
        int thisReadOp = 0;
        while ((thisReadOp = is.read(buf)) > -1) {
            os.write(buf, 0, thisReadOp);
        }
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ioex1) {
            logger.debug("Failed to close stream", ioex1);
        }
        try {
            os.close();
        } catch (IOException ioex2) {
            logger.debug("Failed to close stream", ioex2);
        }
    }
    logger.debug("Retrieved {} to {}", f, outputPath);
}
 
Example 6
private void writeCurrentOptions( String fileName ) {
    try {
        String curOptions = fp.getCurrentOptions();
        BufferedOutputStream bos =
          new BufferedOutputStream( new FileOutputStream( fileName ));
        /// Prepend title and the option that is only obtainable here
        int range[] = rm.getSelectedRange();
        String completeOptions =
          ( "Font2DTest Option File\n" +
            displayGridCBMI.getState() + "\n" +
            force16ColsCBMI.getState() + "\n" +
            showFontInfoCBMI.getState() + "\n" +
            rm.getSelectedItem() + "\n" +
            range[0] + "\n" + range[1] + "\n" + curOptions + tFileName);
        byte toBeWritten[] = completeOptions.getBytes( "UTF-16" );
        bos.write( toBeWritten, 0, toBeWritten.length );
        bos.close();
    }
    catch ( Exception ex ) {
        fireChangeStatus( "ERROR: Failed to Save Options File; See Stack Trace", true );
        ex.printStackTrace();
    }
}
 
Example 7
/**
 * Copies the data in an input stream to a target file if the magic number matches.
 *
 * If the magic number does not match the expected value, this method throws an
 * IOException. Other usual conditions for IOException or FileNotFoundException
 * also apply.
 *
 * @param input the stream to be copied.
 * @param output an output stream to copy the data to.
 */
public static void checkMagicAndCopyFileTo(final BufferedInputStream input,
        final BufferedOutputStream output) throws FileNotFoundException, IOException {
    // Check the magic number
    final int length = MAGIC_NUMBER_VERSION_2.length;
    final byte[] magicNumberBuffer = new byte[length];
    final int readMagicNumberSize = input.read(magicNumberBuffer, 0, length);
    if (readMagicNumberSize < length) {
        throw new IOException("Less bytes to read than the magic number length");
    }
    if (SHOULD_VERIFY_MAGIC_NUMBER) {
        if (!Arrays.equals(MAGIC_NUMBER_VERSION_2, magicNumberBuffer)) {
            if (!Arrays.equals(MAGIC_NUMBER_VERSION_1, magicNumberBuffer)) {
                throw new IOException("Wrong magic number for downloaded file");
            }
        }
    }
    output.write(magicNumberBuffer);

    // Actually copy the file
    final byte[] buffer = new byte[FILE_READ_BUFFER_SIZE];
    for (int readBytes = input.read(buffer); readBytes >= 0; readBytes = input.read(buffer)) {
        output.write(buffer, 0, readBytes);
    }
    input.close();
}
 
Example 8
public static void is2OsNotCloseOs(InputStream is, BufferedOutputStream bos)
throws IOException {
	BufferedInputStream bis = new BufferedInputStream(is);
	byte[] barr = new byte[32768];
	int read = 0;
	while ((read = bis.read(barr)) > 0) {
		bos.write(barr, 0, read);
	}
	close(bis, is);
	bos.flush();
}
 
Example 9
Source Project: PacketProxy   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static void writefile(String filename, byte[] data) throws Exception
{
	FileOutputStream fos = new FileOutputStream(filename);
	BufferedOutputStream bos = new BufferedOutputStream(fos);
	bos.write(data);
	bos.flush();
	bos.close();
}
 
Example 10
Source Project: fingen   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void unzip(String zipFile, String outputFile) throws IOException {
    try {
        ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
        try {
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {

                if (ze.isDirectory()) {
                    File unzipFile = new File(outputFile);
                    if(!unzipFile.isDirectory()) {
                        unzipFile.mkdirs();
                    }
                }
                else {
                    FileOutputStream fout = new FileOutputStream(outputFile, false);
                    BufferedOutputStream bufout = new BufferedOutputStream(fout);
                    try {

                        byte[] buffer = new byte[2048];
                        int read;
                        while ((read = zin.read(buffer)) != -1) {
                            bufout.write(buffer, 0, read);
                        }
                    }
                    finally {
                        zin.closeEntry();
                        bufout.close();
                        fout.close();
                    }
                }
            }
        }
        finally {
            zin.close();
        }
    }
    catch (Exception e) {
        Log.e(TAG, "Unzip exception", e);
    }
}
 
Example 11
/**
 * Extracts a zip entry (file entry)
 * @param zipIn
 * @param filePath
 * @throws IOException
 */
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);
    }
    bos.close();
}
 
Example 12
Source Project: java-n-IDE-for-Android   File: Util.java    License: Apache License 2.0 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 13
@Override
public final void saveBlock(BufferedOutputStream stream) throws IOException {
    // write block type
    stream.write(GeoStructure.TYPE_COMPLEX_L2D);

    // write block data
    stream.write(_buffer, 0, GeoStructure.BLOCK_CELLS * 3);
}
 
Example 14
Source Project: code   File: BufferedOutputStreamDemo.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream("bos.txt"));

    // 写数据
    bos.write("hello".getBytes());

    // 释放资源
    bos.close();
}
 
Example 15
Source Project: AndroidDownload   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 复制文件或目录
 */
public static boolean copy(File src, File tar) {
    try {
        LogUtils.verbose(String.format("copy %s to %s", src.getAbsolutePath(), tar.getAbsolutePath()));
        if (src.isFile()) {
            InputStream is = new FileInputStream(src);
            OutputStream op = new FileOutputStream(tar);
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(op);
            byte[] bt = new byte[1024 * 8];
            while (true) {
                int len = bis.read(bt);
                if (len == -1) {
                    break;
                } else {
                    bos.write(bt, 0, len);
                }
            }
            bis.close();
            bos.close();
        } else if (src.isDirectory()) {
            File[] files = src.listFiles();
            //noinspection ResultOfMethodCallIgnored
            tar.mkdirs();
            for (File file : files) {
                copy(file.getAbsoluteFile(), new File(tar.getAbsoluteFile(), file.getName()));
            }
        }
        return true;
    } catch (Exception e) {
        LogUtils.error(e);
        return false;
    }
}
 
Example 16
public static void is2OS(InputStream is, OutputStream os) throws IOException {
	BufferedOutputStream bos = new BufferedOutputStream(os);
	BufferedInputStream bis = new BufferedInputStream(is);
	byte[] barr = new byte[32768];
	int read = 0;
	try {
		while ((read = bis.read(barr)) != -1) {
			bos.write(barr, 0, read);
		}
	} finally {
		close(bis);
		flushClose(bos);
	}
}
 
Example 17
@Override
public void onPictureTaken(final byte[] data, Camera camera) {
    try {
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filename)));
        out.write(data);
        out.flush();
        out.close();

        if (thumbnail != null) {
            Bitmap thumbnailBitmap = getThumbnail(getContentResolver(), filename);
            FileOutputStream fos = new FileOutputStream(thumbnail);
            thumbnailBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        }

        Intent intent = new Intent();
        intent.putExtra(FILENAME, filename);
        intent.putExtra(THUMBNAIL, thumbnail);
        intent.putExtra(MIMETYPE, "image/*");

        setResult(Activity.RESULT_OK, intent);

        finish();
    } catch (Exception e) {
        e.printStackTrace();
        setResult(Activity.RESULT_CANCELED);
        finish();
    }
    finish();
}
 
Example 18
public static void bArr2File(byte[] barr, String fileName)
throws IOException {
	File file = new File(fileName);
	file.getParentFile().mkdirs();
	File tempFile = new File(fileName + ".tmp");
	FileOutputStream fos = new FileOutputStream(tempFile);
	BufferedOutputStream bos = new BufferedOutputStream(fos);
	try {
		bos.write(barr, 0, barr.length);
	} finally {
		flushClose(bos, fos);
		file.delete();
		tempFile.renameTo(file);
	}
}
 
Example 19
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void rsaDecrypt(Context context, BufferedInputStream inputStream,
                               BufferedOutputStream outputStream) throws NoSuchPaddingException,
        NoSuchAlgorithmException, NoSuchProviderException, CertificateException,
        BadPaddingException, InvalidAlgorithmParameterException, KeyStoreException,
        UnrecoverableEntryException, IllegalBlockSizeException, InvalidKeyException, IOException {

    Cipher cipher = Cipher.getInstance(ALGO_AES, "BC");
    RSAKeygen keygen = new RSAKeygen(context);

    IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, keygen.getSecretKey(), ivParameterSpec);
    CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);

    byte[] buffer = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
    int count;

    try {

        while ((count = cipherInputStream.read(buffer)) != -1) {

            outputStream.write(buffer, 0, count);
            ServiceWatcherUtil.POSITION+=count;
        }
    } finally {

        outputStream.flush();
        outputStream.close();
        cipherInputStream.close();
    }
}
 
Example 20
private void writeNotClose(RandomAccessFile f, byte[] bArr, BufferedOutputStream bos) throws IOException {
	f.readFully(bArr);
	bos.write(bArr);
	bos.flush();
}