Java DataInputStream類

2018-09-18 23:16 更新

Java DataInputStream類

數(shù)據(jù)輸入流允許應(yīng)用程序以與機(jī)器無(wú)關(guān)方式從底層輸入流中讀取基本 Java 數(shù)據(jù)類型。

下面的構(gòu)造方法用來(lái)創(chuàng)建數(shù)據(jù)輸入流對(duì)象。

DataInputStream dis = DataInputStream(InputStream in);

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

序號(hào) 方法描述
1 public final int read(byte[] r, int off, int len)throws IOException
從所包含的輸入流中將 len 個(gè)字節(jié)讀入一個(gè)字節(jié)數(shù)組中。如果len為-1,則返回已讀字節(jié)數(shù)。
2 Public final int read(byte [] b)throws IOException
從所包含的輸入流中讀取一定數(shù)量的字節(jié),并將它們存儲(chǔ)到緩沖區(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é),返回輸入流中兩個(gè)字節(jié)作為對(duì)應(yīng)的基本數(shù)據(jù)類型返回值。
4 public String readLine() throws IOException
從輸入流中讀取下一文本行。

實(shí)例

下面的例子演示了DataInputStream和DataOutputStream的使用,該例從文本文件test.txt中讀取5行,并轉(zhuǎn)換成大寫字母,最后保存在另一個(gè)文件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();
   }
}

以上實(shí)例編譯運(yùn)行結(jié)果如下:

THIS IS TEST 1  ,
THIS IS TEST 2  ,
THIS IS TEST 3  ,
THIS IS TEST 4  ,
THIS IS TEST 5  ,
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)