Java DataOutputStream類
數據輸出流允許應用程序以與機器無關方式將Java基本數據類型寫到底層輸出流。
下面的構造方法用來創建數據輸出流對象。
DataOutputStream out = DataOutputStream(OutputStream out);
創建對象成功後,可以參照以下列表給出的方法,對流進行寫操作或者其他操作。
序號 | 方法描述 |
---|---|
1 | public final void write(byte[] w, int off, int len)throws IOException 將指定字節數組中從偏移量 off 開始的len 個字節寫入此字節數組輸出流。 |
2 | Public final int write(byte [] b)throws IOException 將指定的字節寫入此字節數組輸出流。 |
3 |
|
4 | Public void flush()throws IOException 刷新此輸出流並強制寫出所有緩衝的輸出字節。 |
5 | public final void writeBytes(String s) throws IOException 將字符串以字節序列寫入到底層的輸出流,字符串中每個字符都按順序寫入,並丟棄其高八位。 |
實例
下面的例子演示了DataInputStream和DataOutputStream的使用,該例從文本文件test.txt中讀取5行,並轉換成大寫字母,最後保存在另一個文件test1.txt中。
import java.io.*; public class Test{ public static void main(String args[])throws IOException{ DataInputStream d = new DataInputStream(new FileInputStream("test.txt")); DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt")); String count; while((count = d.readLine()) != null){ String u = count.toUpperCase(); System.out.println(u); out.writeBytes(u + " ,"); } d.close(); out.close(); } }
以上實例編譯運行結果如下:
THIS IS TEST 1 , THIS IS TEST 2 , THIS IS TEST 3 , THIS IS TEST 4 , THIS IS TEST 5 ,