OutputStream (字節流寫出)
java.io.OutputStream
是字節流輸出流的父類,而且是抽象類。所以不能創建對象,
OutputStream常用實現類的繼承關系
- java.lang.Object
java.io.OutputStream
java.io.FileOutputStream
java.io.BufferedOutputStream
OutputStream的常用實現類2個: FileOutputStream和BufferedOutputStream
OutputStream共性方法: (子類通用)
返回值 | 方法 | 說明 |
---|---|---|
void | close() | 關閉此輸出流並釋放與此流有關的所有系統資源。(關閉前會flush) |
void | flush() | 刷新此輸出流並強制寫出所有緩沖的輸出字節。 |
void | write(byte[] b) | 將 b.length 個字節從指定的 byte 數組寫入此輸出流。 |
void | write(byte[] b, int off, int len) | 將指定 byte 數組中從偏移量 off 開始的 len 個字節寫入此輸出流。 |
abstract void | write(int b) | 將指定的字節寫入此輸出流。 |
FileOutputStream子類
構造方法
方法 | 說明 |
---|---|
FileOutputStream(File file) | 傳入一個File對象 |
FileOutputStream(String name) | 傳入一個文件路徑字符串 |
FileOutputStream(File file, boolean append) | 傳入一個File對象, append取值: true: 追加 false: 覆蓋 默認false |
FileOutputStream(String name, boolean append) | 傳入一個文件路徑字符串, append取值: true: 追加 false: 覆蓋 默認false |
使用實例:
try {
// 1. 創建對象--默認是覆蓋模式, 也可以改成追加模式
String path = "D:\\DEV\\eclipse\\workspace\\day13\\testOut.txt";
// 加上true就是追加, 否則是覆蓋
OutputStream out = new FileOutputStream(path, true);
// 第二種創建方式
// OutputStream out = new FileOutputStream(new File(path));
// 2. 開始寫出
out.write(97);
out.write(98);
out.write(99);
// 3. 釋放資源
out.close();
} catch (IOException e) {
e.printStackTrace();
}
BufferedOutputStream子類
該類實現緩沖的輸出流。比FileOutputStream更加高效
構造器
方法 | 說明 |
---|---|
BufferedOutputStream(OutputStream out) | 一般傳入一個FileOutputStream |
使用實例:
try {
// 1. 創建對象
String path = "D:\\DEV\\eclipse\\workspace\\day13\\testOut.txt";
OutputStream out = new BufferedOutputStream(
// 加上true就是追加, 否則是覆蓋
new FileOutputStream(path,true)
);
// 2. 開始寫入
out.write(97);
out.write(98);
out.write(99);
// 3. 關閉資源
out.close();
} catch (IOException e) {
e.printStackTrace();
}