Java DataInputStream類
數據輸入流允許應用程序以與機器無關方式從底層輸入流中讀取基本Java 數據類型。
下面的構造方法用來創建數據輸入流對象。
DataInputStream dis = DataInputStream(InputStream in);
另一種創建方式是接收一個字節數組,和兩個整形變量off、len,off表示第一個讀取的字節,len表示讀取字節的長度。
序號 | 方法描述 |
---|---|
1 | public final int read(byte[] r, int off, int len)throws IOException 從所包含的輸入流中將 len 個字節讀入一個字節數組中。 如果len為-1,則返回已讀字節數。 |
2 | Public final int read(byte [] b)throws IOException 從所包含的輸入流中讀取一定數量的字節,並將它們存儲到緩衝區數組 b 中。 |
3 |
|
4 | public String readLine() 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 ,