Java中的DataInputStream类

数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。

下面的构造方法用来创建数据输入流对象。

DataInputStream dis = new DataInputStream(InputStream in);

另一种创建方式是接收一个字节数组,和两个整形变量 off、len,off 表示第一个读取的字节,len 表示读取字节的长度。

方法描述
public final int read(byte[] r, int off, int len)throws IOException
从所包含的输入流中将 len 个字节读入一个字节数组中。如果 len 为-1,则返回已读字节数。
Public final int read(byte [] b)throws IOException
从所包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 b 中。
  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

从输入流中读取字节,返回输入流中两个字节作为对应的基本数据类型返回值。

public String readLine() throws IOException
从输入流中读取下一文本行。

实例

下面的例子演示了 DataInputStream 和 DataOutputStream 的使用,该例从文本文件 test.txt 中读取 5 行,并转换成大写字母,最后保存在另一个文件 test1.txt 中。

test.tx 文件内容如下:

mybj1
mybj2
mybj3
mybj4
mybj5

java 代码:

import java.io.*;
 
public class Test{
   public static void main(String args[])throws IOException{
 
      DataInputStream in = new DataInputStream(new FileInputStream("test.txt"));
      DataOutputStream out = new DataOutputStream(new  FileOutputStream("test1.txt"));
      BufferedReader d  = new BufferedReader(new InputStreamReader(in));
     
      String count;
      while((count = d.readLine()) != null){
          String u = count.toUpperCase();
          System.out.println(u);
          out.writeBytes(u + "  ,");
      }
      d.close();
      out.close();
   }
}

以上实例编译运行结果如下:

MYBJ1
MYBJ2
MYBJ3
MYBJ4
MYBJ5

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Java中的DataInputStream类

发表回复