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

The following examples show how to use java.io.BufferedOutputStream#flush() . 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: EasyPhotos   File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "IMG_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 2
/**
 * Handle image processing in Firebase and Cloud Vision.
 */
private void onPictureTaken(final byte[] imageBytes) {
    Log.d(TAG, "PhotoCamera onPictureTaken");
    if (imageBytes != null) {
        String imageStr = Base64.encodeToString(imageBytes, Base64.NO_WRAP | Base64.URL_SAFE);
        Log.d(TAG, "imageBase64:"+imageStr);

        final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        if (bitmap != null) {
            File file=new File(HttpServer.wwwRoot + "pic.jpg");//将要保存图片的路径
            try {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                bos.flush();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            picVersion++;
        }
    }
}
 
Example 3
Source Project: AlbumCameraRecorder   File: FileUtil.java    License: MIT License 6 votes vote down vote up
public static String saveBitmap(String dir, Bitmap b) {
    DST_FOLDER_NAME = dir;
    String path = initPath();
    long dataTake = System.currentTimeMillis();
    String jpegName = path + File.separator + "picture_" + dataTake + ".jpg";
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        return jpegName;
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example 4
public static void saveBackgroundImage(Context ctx, String filePath,
                                       Bitmap bitmap, int quality) throws IOException {
    if (bitmap != null) {
        File file = new File(filePath.substring(0,
                filePath.lastIndexOf(File.separator)));
        if (!file.exists()) {
            file.mkdirs();
        }
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(filePath));
        bitmap.compress(CompressFormat.PNG, quality, bos);
        bos.flush();
        bos.close();
        if (ctx != null) {
            scanPhoto(ctx, filePath);
        }
    }
}
 
Example 5
Source Project: joyqueue   File: Base64.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 使用输入输出流编码
 *
 * @param in      输入流
 * @param out     输出流
 * @param options 编码参数,使用或操作并BASE64.[X]
 * @throws IOException
 */
public static void encode(final InputStream in, final OutputStream out, final int options) throws IOException {
    byte[] encodeMap = getEncodeTable(options);
    boolean breakLine = (options & ENCODE_BREAK_LINE) != 0;
    int lineSize = LINE_MAX / 4;
    byte[] buff = new byte[4];
    BufferedInputStream bin = new BufferedInputStream(in);
    BufferedOutputStream bout = new BufferedOutputStream(out);
    byte[] data = new byte[3];
    int readCnt;
    int solveCnt = 0;
    while ((readCnt = bin.read(data)) != -1) {
        if (readCnt > 0) {
            if (breakLine && solveCnt > 0 && solveCnt % lineSize == 0) {
                bout.write(NEW_LINE);
            }
            byte3to4(encodeMap, data, 0, readCnt, buff, 0);
            bout.write(buff);
            solveCnt++;
        }
    }
    bout.flush();
}
 
Example 6
Source Project: pxf   File: HiveBinaryDataGen.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws IOException {
    try {
        FileOutputStream outputStream = new FileOutputStream("src/test/resources/data/hive/hiveBinaryData");
        BufferedOutputStream out = new BufferedOutputStream(outputStream);
        try {
            for (int i = 0; i < 256; i++) {
                out.write(i);
            }
            out.flush();
        } finally {
            out.close();
        }
    } catch (IOException ex) {
        System.out.println (ex.toString());
    }
}
 
Example 7
public static byte[] serialize(final StandardSnippet snippet) {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(baos);

        JAXBContext context = JAXBContext.newInstance(StandardSnippet.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(snippet, bos);

        bos.flush();
        return baos.toByteArray();
    } catch (final IOException | JAXBException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example 8
/**
 * This method when called assumes the Framework Nar ClassLoader is in the
 * classloader hierarchy of the current context class loader.
 * @param dto the template dto to serialize
 * @return serialized representation of the DTO
 */
public static byte[] serialize(final TemplateDTO dto) {
    try {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final BufferedOutputStream bos = new BufferedOutputStream(baos);

        JAXBContext context = JAXBContext.newInstance(TemplateDTO.class);
        Marshaller marshaller = context.createMarshaller();
        XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
        XMLStreamWriter writer = new IndentingXMLStreamWriter(xmlof.createXMLStreamWriter(bos));
        marshaller.marshal(dto, writer);

        bos.flush();
        return baos.toByteArray(); //Note: For really large templates this could use a lot of heap space
    } catch (final IOException | JAXBException | XMLStreamException e) {
        throw new FlowSerializationException(e);
    }
}
 
Example 9
Source Project: FaceDemo   File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 保存一个暂时的bitmap图片
 *
 * 保存目录在
 * @param b
 */
public static String saveTmpBitmap(Bitmap b,String name){
    String result= "";
    String jpegName = MyConfig.ROOT_CACHE+File.separator+MyConfig.FACE_DIR +File.separator+name +".jpg";
    Log.d("FileUtil",jpegName);
    result = jpegName;
    try {
        FileOutputStream fout = new FileOutputStream(jpegName);
        BufferedOutputStream bos = new BufferedOutputStream(fout);
        b.compress(Bitmap.CompressFormat.JPEG, 100 , bos);
        bos.flush();
        bos.close();
        Log.i(TAG, "暂存的 saveBitmap成功");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i(TAG, "暂存的saveBitmap失败");
        e.printStackTrace();
    }
    return result;
}
 
Example 10
Source Project: sdb-mall   File: StorageManager.java    License: Apache License 2.0 5 votes vote down vote up
public static State saveFileByInputStream(InputStream is, String path) {
	State state = null;

	File tmpFile = getTmpFile();

	byte[] dataBuf = new byte[ 2048 ];
	BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);

	try {
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);

		int count = 0;
		while ((count = bis.read(dataBuf)) != -1) {
			bos.write(dataBuf, 0, count);
		}
		bos.flush();
		bos.close();

		state = saveTmpFile(tmpFile, path);

		if (!state.isSuccess()) {
			tmpFile.delete();
		}

		return state;
	} catch (IOException e) {
	}
	return new BaseState(false, AppInfo.IO_ERROR);
}
 
Example 11
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 12
Source Project: Deta_DataBase   File: UnZip.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static void unZipWithPath(String zipFullPath, String zipCategory) {
	try {
		String fileName = zipFullPath; //��Ҫ��ѹ���ļ�zip��ַ
		//String filePath = zipCategory; //��ѹ����ַ
		ZipFile zipFile = new ZipFile(fileName);
		Enumeration emu = zipFile.entries();
		while(emu.hasMoreElements()){
			ZipEntry entry = (ZipEntry)emu.nextElement();
			if (entry.isDirectory()){
				//new File(filePath + entry.getName()).mkdirs();
				new File(entry.getName()).mkdirs();
				continue;
			}
			BufferedInputStream bufferedInputStream = new BufferedInputStream(zipFile.getInputStream(entry));
			File file = new File(entry.getName());
			File parent = file.getParentFile();
			if(parent != null && (!parent.exists())){
				parent.mkdirs();
			}
			if(!file.getPath().contains(".lyg")) {
				file.mkdirs();
			}else {
				FileOutputStream fileOutputStream = new FileOutputStream(file);
				BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream,BUFFER);           
				int count;
				byte data[] = new byte[BUFFER];
				while ((count = bufferedInputStream.read(data, 0, BUFFER)) != -1){
					bufferedOutputStream.write(data, 0, count);
				}
				bufferedOutputStream.flush();
				bufferedOutputStream.close();
			}
			bufferedInputStream.close();	
		}
		zipFile.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Source Project: org.hl7.fhir.core   File: NpmPackage.java    License: Apache License 2.0 5 votes vote down vote up
public static NpmPackage fromZip(InputStream stream, boolean dropRootFolder, String desc) throws IOException {
  NpmPackage res = new NpmPackage();
  ZipInputStream zip = new ZipInputStream(stream);
  ZipEntry ze;
  while ((ze = zip.getNextEntry()) != null) {
    int size;
    byte[] buffer = new byte[2048];

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(bytes, buffer.length);

    while ((size = zip.read(buffer, 0, buffer.length)) != -1) {
      bos.write(buffer, 0, size);
    }
    bos.flush();
    bos.close();
    if (bytes.size() > 0) {
      if (dropRootFolder) {
        res.loadFile(ze.getName().substring(ze.getName().indexOf("/")+1), bytes.toByteArray());
      } else {
        res.loadFile(ze.getName(), bytes.toByteArray());
      }
    }
    zip.closeEntry();
  }
  zip.close();         
  try {
    res.npm = JsonTrackingParser.parseJson(res.folders.get("package").fetchFile("package.json"));
  } catch (Exception e) {
    throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
  }
  res.checkIndexed(desc);
  return res;
}
 
Example 14
Source Project: timecat   File: IOUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void saveToFile(InputStream in, String file) throws IOException {
    File outputFile = new File(file);
    outputFile.deleteOnExit();
    outputFile.getParentFile().mkdirs();
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
    byte[] buffer = new byte[2048];
    int length = in.read(buffer);
    while (length != -1) {
        outputStream.write(buffer, 0, length);
        length = in.read(buffer);
    }
    outputStream.flush();
    outputStream.close();
}
 
Example 15
@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 16
/**
 * Helper method to decrypt file
 * @param inputStream stream associated with encrypted file
 * @param outputStream stream associated with new output decrypted file
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static void aesDecrypt(BufferedInputStream inputStream, BufferedOutputStream outputStream)
        throws NoSuchPaddingException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyStoreException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance(ALGO_AES);
    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, IV.getBytes());

    cipher.init(Cipher.DECRYPT_MODE, getSecretKey(), gcmParameterSpec);
    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();
        cipherInputStream.close();
        outputStream.close();
    }
}
 
Example 17
public static void main(String[] args) throws IOException {
  FileOutputStream out = new FileOutputStream(FileDescriptor.out);
  BufferedOutputStream o2 = new BufferedOutputStream(out, 1024);

  for (int i = 0; i < 10240; i++) {
    o2.write(i % 26 + 'a');
    if (i % 1024 == 0) {
      o2.write('\n');
    }
  }

  o2.flush();
  o2.close();
}
 
Example 18
Source Project: hop   File: XmlHandler.java    License: Apache License 2.0 5 votes vote down vote up
public static String encodeBinaryData( byte[] val ) throws IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  GZIPOutputStream gzos = new GZIPOutputStream( baos );
  BufferedOutputStream bos = new BufferedOutputStream( gzos );
  bos.write( val );
  bos.flush();
  bos.close();

  return new String( Base64.encodeBase64( baos.toByteArray() ) );
}
 
Example 19
Source Project: styT   File: SessionThread.java    License: Apache License 2.0 5 votes vote down vote up
public void writeBytes(byte[] bytes) {
    try {
        // TODO: do we really want to do all of this on each write? Why?
        BufferedOutputStream out = new BufferedOutputStream(cmdSocket
                .getOutputStream(), Defaults.dataChunkSize);
        out.write(bytes);
        out.flush();
        dataSocketFactory.reportTraffic(bytes.length);
    } catch (IOException e) {
     //   myLog.l(Log.INFO, "Exception writing socket");
        closeSocket();
        return;
    }
}
 
Example 20
/**
 * Writes the <code>toString()</code> value of each item in a collection to
 * the specified <code>File</code> line by line.
 * The specified character encoding and the line ending will be used.
 *
 * @param file  the file to write to
 * @param encoding  the encoding to use, {@code null} means platform default
 * @param lines  the lines to write, {@code null} entries produce blank lines
 * @param lineEnding  the line separator to use, {@code null} is system default
 * @param append if {@code true}, then the lines will be added to the
 * end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
 * @since 2.1
 */
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding, boolean append)
        throws IOException {
    FileOutputStream out = null;
    try {
        out = openOutputStream(file, append);
        final BufferedOutputStream buffer = new BufferedOutputStream(out);
        IOUtils.writeLines(lines, lineEnding, buffer, encoding);
        buffer.flush();
        out.close(); // don't swallow close Exception if copy completes normally
    } finally {
        IOUtils.closeQuietly(out);
    }
}