在上篇文章中我們提及到,輸出流往往和某些數據的目標媒介相關聯,如文件、網絡連接、管道等。 當寫入到輸出流的數據逐漸輸出完畢時,目標媒介是所有數據的歸屬地。
- outputStream 和 write 兩個流都採用瞭如下方法:
- void write(int b) : 將指定流的字節/字符輸出到輸出流中
- void write(byte b[]) :將字節數組/字符數組中的數據輸出到指定輸出流中
- void write(byte b[], int off, int len) : 將字節/字符數組中從off位置開始,長度爲len的字節/字符輸出到輸出流中。
因爲字符流直接以字符爲操作單位,所以writer可以用字符來代替字符數組,即以String對象作爲參數:
- voidwrite(String str)
- voidwrite(String str, int off, intlen)
outputStream 的子類可能會包含write()方法的替代方法,比如,DataOutputStream 允許使用writeBoolean() ,writeDouble () 等方法將基本類型int、long、float、boolean 等變量寫入。
下面是outputStream 實例:
/**
* java io outputStream example
*
* @author mingx
*
*/
public class FileOutputStreamExample {
public static void main(String[] args) throws IOException {
FileInputStream fin = null;
FileOutputStream fou = null;
try {
fin = new FileInputStream("D:\\ZhyTestSpace\\testBase\\src\\test\\java\\testBase\\UserTest.java");
fou = new FileOutputStream("E:\\javaFile\\newFile.txt");
byte[] bbuf = new byte[32];
int count = 0;
// 循環從流中取出數據
while ((count = fin.read(bbuf)) > 0) {
// 每讀取一次,即寫入文件輸出流,讀多少,寫多少
fou.write(bbuf, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fin != null) {
fin.close(); // 關閉文件輸入流
}
if (fou != null) {
fou.close(); // 關閉文件輸出流
}
}
}
}
運行上面的程序,在E:\javaFile 路徑下多了個newFile.txt 文件,該文件的內容與UserTest.java 文件的內容完全相同。
注意: 當結束數據寫入時,需要關閉outputStream ,即調用close() 方法,因爲outputStream 的各種write()方法可能會拋出IO異常,所以需要把調用close()方法放在finally 塊中執行。
下面是Writer 實例 :
/**
* java io API Writer example
*
* @author mingx
*
*/
public class WriterExample {
public static void main(String[] args) throws IOException{
FileWriter fw = null;
try {
fw = new FileWriter("E:\\javaFile\\pom.txt");
fw.write("春曉-孟浩然\r\n");
fw.write("春眠不覺曉,處處聞啼鳥。\r\n");
fw.write("夜來風雨聲,花落知多少。 \r\n");
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(fw !=null){
fw.close();
}
}
}
}
Write 適用於直接輸出字符串內容,運行上面程序,在E:\javaFile 目錄下會輸出一個pom.txt 文件。 文件內容就是程序中輸出的內容。