1 位元組流抽象基類
InputStream 位元組輸入流所有類的超類
OutputStream 位元組輸出流所有類的超類
2 FileOutputStream(String name) 建立檔案輸出流以指定的名稱寫入檔案
void close() 關閉此檔案輸出流并釋放與此流相關聯的任何系統資源
public class demo1 {
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("fos.txt");
fos.write(97);
fos.close();
}
3 位元組流寫資料的三種方式
void write(int b) 将指定的位元組寫入此檔案輸出流,一次寫一個位元組資料
void write(byte[] b) 将b.length位元組從指定的位元組數組寫入此檔案輸出流,一次寫一個位元組數組資料
byte[] bys= {97,98,99,100}; //另一種建立位元組數組的方法 byte[] getBytes() 傳回字元串對應的位元組數組
fos.write(bys); //byte[] bys="abcd".getBytes();
fos.close();
void write(byte[] b,int off,int len)将len位元組從指定的位元組數組開始,從偏移量off開始寫入此檔案輸出流
一次寫一個位元組數組的部分資料
byte[] bys="abcd".getBytes();
fos.write(bys,0,bys.length);
4 位元組流寫資料如何換行
位元組流寫資料如何追加
public FileOutputStream(String name,boolean append)
建立檔案輸出流以指定的名稱寫入檔案,
如果第二個參數是true,位元組将寫入檔案的末尾,而不是開頭
FileOutputStream fos=new FileOutputStream("fox.txt",true);
byte[] bys="hello".getBytes();
for(int i=0;i<10;i++)
fos.write(bys);
fos.write("\n".getBytes());
5 位元組流寫資料加異常處理
package com;
import java.io.FileOutputStream;
import java.io.IOException;
public class demo {
public static void main(String[] args)
{
FileOutputStream fos=null;//fos如果在下面的try裡定義,finally裡沒法用
try {
fos=new FileOutputStream("fos.txt");
fos.write("hello".getBytes());
}catch(IOException e)
{
e.printStackTrace();
}finally {
if(fos!=null)//防止空指針異常
{
try {
fos.close();
}catch(IOException e)
e.printStackTrace();
}
}
}