DataOutputStreamStream使您可以将原语写入输出源。以下是创建DataOutputStream的构造函数。
DataOutputStream out=DataOutputStream(OutputStream out);
拥有DataOutputStream对象后,便会出现一个辅助方法列表,可用于编写流或对该流执行其他操作。
| Sr.No. | Method & Remark |
|---|---|
| 1 |
public final void write(byte [] w,int off,int len) throws IOException 从指定的点数组(从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 void flush() throws IOException 刷新数据输出流。 |
| 5 |
public final void writeBytes(String s) throws IOException 将字符串作为字节序列写出到基础输出流中。 |
以下是演示DataInputStream和DataOutputStream的示例。 本示例读取文件test.txt中给出的5行,并将这些行转换为大写字母,最后将它们复制到另一个文件test1.txt中。
import java.io.*;
public class DataInput_Stream {
public static void main(String args[])throws IOException {
// 将字符串写入编码为修改后的 UTF-8 的文件
DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("E:\\file.txt"));
dataOut.writeUTF("hello");
// 从同一个文件中读取数据
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 ,