java中讲讲DataInputStream的用法,举例?

本文详细介绍DataInputStream和DataOutputStream的使用方法,通过实例演示如何将int、double和UTF字符串写入文件,再从同一文件中按顺序读取这些数据。强调了读写操作的顺序一致性,对于理解Java中数据流的读写机制至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2.4 DataInputStream的用法 
DataInputStream顾名思义:就是专门用来读各种各样的数据的,比如(int,char,long等),一定要注意 DataOutputStream 与DataInputStream配合使用,而且二者读写的顺序要一样,可以参照下面的例子。

例:2.4.1

import java.io.*;
public class TestMark_to_win {
    /* when run this program, no need any data.dat file, because it can generate
the file.anyway,this file can not be recognized by humanbeing
*/
    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("c:/data.txt");

        DataOutputStream dos = new DataOutputStream(fos);

        dos.writeInt(345);

        dos.writeDouble(4.54);

        dos.writeUTF("我们");
        dos.close();

        FileInputStream fis = new FileInputStream("c:/data.txt");
        DataInputStream dis = new DataInputStream(fis);
        /*1) a data output stream to write data that can later
be read by a data input stream. 2)note the sequence.first write what,
then read what. if you comment out the following statment,the result
is not correct, because the sequence is chaotic.I tried. 3) readInt()
Returns: the next four bytes of this input stream, interpreted as an
int. */
       

更多请见:http://www.mark-to-win.com/tutorial/java_8_UsageOfDataInputStream.html

`java.io.DataInputStream`是Java标准库中用于读取二进制文件的类,它允许以一种更自然的方式处理字节流,而不是直接操作`byte[]`数组。下面是一个的例子,说明如何使用`DataInputStream`来读取二进制文件: ```java import java.io.*; import java.io.DataInputStream; public class DataInputStreamExample { public static void main(String[] args) { try { // 打开一个二进制文件(假设文件名为"data.bin") FileInputStream fis = new FileInputStream("data.bin"); // 创建DataInputStream实例,将FileInputStream传递给它 DataInputStream dis = new DataInputStream(fis); // 读取整型数值 int num = dis.readInt(); // 读取4个字节的数据作为整数 // 读取浮点数 float floatNum = dis.readFloat(); // 读取字符串(注意字节序) byte[] strBytes = new byte[5]; dis.readFully(strBytes); String str = new String(strBytes, "UTF-8"); // 解码字符串 // 关闭输入流 dis.close(); fis.close(); System.out.println("Read number: " + num); System.out.println("Read float: " + floatNum); System.out.println("Read string: " + str); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个例子中,我们首先创建了`FileInputStream`来打开文件,然后创建`DataInputStream`来处理读取操作。`readInt()`和`readFloat()`分别用于读取基本数据类型,`readFull()`则可以一次性读取指定长度的数据到缓冲区。记得在完成操作后关闭`DataInputStream`和`FileInputStream`以释放资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值