Java DataOutputStream類
數據輸出流允許應用程式以與機器無關方式將Java基本數據類型寫到底層輸出流。
下麵的構造方法用來創建數據輸出流對象。
DataOutputStream out = new 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中。
test.tx 檔內容如下:
zaixian1 zaixian2 zaixian3 zaixian4 zaixian5
實例
import java.io.*;
public class Test{
public static void main(String args[])throws IOException{
DataInputStream in = new DataInputStream(new FileInputStream("test.txt"));
DataOutputStream out = new DataOutputStream(new FileOutputStream("test1.txt"));
BufferedReader d = new BufferedReader(new InputStreamReader(in));
String count;
while((count = d.readLine()) != null){
String u = count.toUpperCase();
System.out.println(u);
out.writeBytes(u + " ,");
}
d.close();
out.close();
}
}
以上實例編譯運行結果如下:
zaixian1 zaixian2 zaixian3 zaixian4 zaixian5