天天看點

BufferedOutputStream應用

源碼

package com.io;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * @author yanyugang
 * @description
 * 1、BufferedOutputStream建立檔案
 * 2、BufferedOutputStream寫入内容,檔案末尾,追加方式
 * @date 2019/10/13 15:15
 */
public class BufferedOutputStreamTest {
    public static void main(String[] args) {
        // 檔案路徑
        String path = "D:" + File.separator + "bufferedoutputstream.txt";
        BufferedOutputStreamWirteFile(path);
    }

    private static void BufferedOutputStreamWirteFile(String path) {
        // JDK7 try-with-resources 自動釋放資源
        // BufferedOutputStream 有緩沖區,含有位元組數組buf,預設大小8192,緩沖區滿了,再寫入檔案1
        try (
                OutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path), true))) {
            StringBuffer buf = new StringBuffer();
            buf.append("Hello World!").append("\r\n");
            buf.append("Hello Java!").append("\r\n");
            buf.append("Hello Shao Yv!").append("\r\n");
            buf.append("Hello Jing Tianming!").append("\r\n");
            buf.append("Hello Gao Yue!").append("\r\n");
            bos.write(buf.toString().getBytes());
            bos.write(buf.toString().getBytes());
            bos.write(buf.toString().getBytes());
            // 清空緩沖區,寫入到檔案中
            bos.flush();
        } catch (
                Exception e) {
        }
    }
}

           

繼續閱讀