Java DataOutputStream类
DataOutputStream流允许将原始数据写入输出源。
以下是创建DataOutputStream的构造方法。
DataOutputStream out = DataOutputStream(OutputStream out);
一旦你手头有了 DataOutputStream 对象,那么就有一系列辅助方法可以用来写入流或对流进行其他操作。
| 序号 | 方法与说明 | 
|---|---|
| 1 | public final void write(byte[] w, int off, int len)throws IOException 从指定的字节数组w的off偏移处开始,将len个字节写入底层流。 | 
| 2 | Public final int write(byte [] b)throws IOException 将当前写入此数据输出流的字节数返回。返回写入缓冲区的总字节数。 | 
| 3 | (a) public final void writeBooolean()throws IOException, (b) public final void writeByte()throws IOException, (c) public final void writeShort()throws IOException (d) public final void writeInt()throws IOException 这些方法将特定原始类型数据以字节形式写入输出流。 | 
| 4 | Public void flush()throws IOException 刷新数据输出流。 | 
| 5 | public final void writeBytes(String s) throws IOException 将字符串作为字节序列写入底层输出流。字符串中的每个字符都按顺序写入,并且丢弃其高8位。 | 
示例
下面是一个示例,演示了DataInputStream和DataOutputStream的用法。此示例从文件test.txt中读取5行,并将这些行转换为大写字母,最后将它们复制到另一个文件test1.txt中。
import java.io.*;
public class DataInput_Stream {
   public static void main(String args[])throws IOException {
      // writing string to a file encoded as modified UTF-8
      DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
      dataOut.writeUTF("hello");
      // Reading data from the same file
      DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));
      while(dataIn.available()>0) {
         String k = dataIn.readUTF();
         System.out.print(k+" ");
      }
   }
}
这是上述程序的示例运行 –
输出
THIS IS TEST 1  ,
THIS IS TEST 2  ,
THIS IS TEST 3  ,
THIS IS TEST 4  ,
THIS IS TEST 5  ,
极客教程