Java DataOutputStream類

2018-09-11 01:18 更新

Java DataOutputStream類

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

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

DataOutputStream out = DataOutputStream(OutputStream  out);

創(chuàng)建對(duì)象成功后,可以參照以下列表給出的方法,對(duì)流進(jìn)行寫操作或者其他操作。

序號(hào) 方法描述
1 public final void write(byte[] w, int off, int len)throws IOException
將指定字節(jié)數(shù)組中從偏移量 off 開(kāi)始的 len 個(gè)字節(jié)寫入此字節(jié)數(shù)組輸出流。
2 Public final int write(byte [] b)throws IOException
將指定的字節(jié)寫入此字節(jié)數(shù)組輸出流。
3
  1. public final void writeBooolean()throws IOException,
  2. public final void writeByte()throws IOException,
  3. public final void writeShort()throws IOException,
  4. public final void writeInt()throws IOException
這些方法將指定的基本數(shù)據(jù)類型以字節(jié)的方式寫入到輸出流。
4 Public void flush()throws IOException
  刷新此輸出流并強(qiáng)制寫出所有緩沖的輸出字節(jié)。
5 public final void writeBytes(String s) throws IOException
將字符串以字節(jié)序列寫入到底層的輸出流,字符串中每個(gè)字符都按順序?qū)懭?,并丟棄其高八位。

實(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)