java inputdata类_Java DataInputStream类

DataInputStream类用于在DataOutputStream类的上下文中,可用于读取原始数据。

以下是创建DataInputStream的构造函数 -

InputStream in = new DataInputStream(InputStream in);

当创建了DataInputStream对象,就可以使用一些它的辅助方法来读取流或在流上执行其他操作。

编号

方法

描述

1

public final int read(byte[] r, int off, int len)throws IOException

将输入流中最多len个字节的数据读入一个字节数组。 返回读入缓冲区的总字节数,否则返回-1(如果它是文件末尾)。

2

public final int read(byte [] b)throws IOException

从输入流中读取一些字节并存储到字节数组中。 返回读入缓冲区的总字节数,否则返回-1(如果它是文件末尾)。

3

public final Boolean readBooolean()throws IOException,public final byte readByte()throws IOException,public final short readShort()throws IOException,public final Int readInt()throws IOException

这些方法将从包含InputStream中读取字节。返回InputStream后两个字节作为指定原始类型。

4

public String readLine() throws IOException

从输入流中读取下一行文本。 它读取连续的字节,将每个字节分别转换为字符,直到它遇到行终止符或文件结尾; 然后读取的字符作为String返回。

示例

以下是演示如何使用DataInputStream和DataOutputStream的示例。 此示例将字符串写入指定文件中,然后再从文件test.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\n");

dataOut.writeUTF("yiibai\n");

// 从指定文件中读取内容

DataInputStream dataIn = new DataInputStream(new FileInputStream("E:\\file.txt"));

while (dataIn.available() > 0) {

String str = dataIn.readUTF();

System.out.print(str);

}

}

}

执行上面示例代码,得到以下结果 -

hello

yiibai

¥ 我要打赏

纠错/补充

收藏

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值