Java DataInputStream類

Java 流(Stream) Java 流(Stream)


數據輸入流允許應用程式以與機器無關方式從底層輸入流中讀取基本 Java 數據類型。

下麵的構造方法用來創建數據輸入流對象。

DataInputStream dis = new 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
  1. public final Boolean readBooolean()throws IOException,
  2. public final byte readByte()throws IOException,
  3. public final short readShort()throws IOException
  4. public final Int readInt()throws IOException
從輸入流中讀取位元組,返回輸入流中兩個位元組作為對應的基本數據類型返回值。
4 public String readLine() 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

Java 流(Stream) Java 流(Stream)