Java DataInputStream類

2018-09-18 23:16 更新

Java DataInputStream類

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

下面的構造方法用來創(chuàng)建數(shù)據輸入流對象。

DataInputStream dis = DataInputStream(InputStream in);

另一種創(chuàng)建方式是接收一個字節(jié)數(shù)組,和兩個整形變量 off、len,off表示第一個讀取的字節(jié),len表示讀取字節(jié)的長度。

序號 方法描述
1 public final int read(byte[] r, int off, int len)throws IOException
從所包含的輸入流中將 len 個字節(jié)讀入一個字節(jié)數(shù)組中。如果len為-1,則返回已讀字節(jié)數(shù)。
2 Public final int read(byte [] b)throws IOException
從所包含的輸入流中讀取一定數(shù)量的字節(jié),并將它們存儲到緩沖區(qū)數(shù)組 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
從輸入流中讀取字節(jié),返回輸入流中兩個字節(jié)作為對應的基本數(shù)據類型返回值。
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  ,
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號