Java IO 中整数数据类型的使用与存储

更新时间:2024-04-07 16:00:36   人气:9768
在 Java 输入/输出 (IO) 流处理中,整型数据的读取和写入是基础且常见的操作。Java 提供了丰富的类库来支持不同格式下的整数值进行高效、准确的数据流传输或文件持久化。

### 整形数据的基本 I/O 操作

#### 1. 数据写出(Write)

对于基本类型 `int` 的输出,在Java IO包中的`DataOutputStream`提供了直接的方法:

java

import java.io.*;

public class IntDemo {
public static void main(String[] args) throws IOException {

FileOutputStream fos = new FileOutputStream("output.txt");
DataOutputStream dos = new DataOutputStream(fos);

int valueToSave = 42;

// 将整数以字节形式写出到数据输出流
dos.writeInt(valueToSave);

dos.close();
fos.close();

}
}

上述代码将一个整数值保存到了名为 "output.txt" 的文件里,实际上是以四个连续的字节方式存储,这是因为Java里的`int`占用32位或者说是4个字节。

#### 2. 数据读取(Read)

对应的输入过程可以通过`DataInputStream`实现对之前存出的整数值恢复:

java

import java.io::*;

public class IntDemoReader {
public static void main(String[] args) throws IOException {

FileInputStream fis = new FileInputStream("output.txt");
DataInputStream dis = new DataInputStream(fis);

// 从数据输入流中读取并还原为整形变量
int restoredValue = dis.readInt();

System.out.println(restoredValue);

dis.close();
fis.close();

}
}


这段程序会打开同一个 “output.txt” 文件,并从中取出先前所写的整数值。

### 高级I/O API:NIO Buffers 和 Channels

而在更高级别的Java NIO框架下,可以利用Buffer(缓冲区)结合Channel(通道),同样完成整数与其他原始类型的高性能I/O:

java

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class IntDemoWithNio{
public static void writeInt() throws Exception{
FileChannel channel = new RandomAccessFile("nio_output.dat", "rw").getChannel();

ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.putInt(9876543210);
buffer.flip();

while(buffer.hasRemaining()){
channel.write(buffer);
}

channel.close();
}

public static void readInt() throws Exception{
FileChannel channel = new RandomAccessFile("nio_output.dat","r").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);

if(channel.read(buffer)>0){
buffer.rewind();
int retrievedInteger = buffer.getInt();
System.out.println(retrievedInteger);
}

channel.close();
}
}

// 使用方法:
try {
IntDemoWithNio.writeInt();
} catch(Exception e){...}
...
try{
IntDemoWithNio.readInt();
}catch(Exception e){...}


以上示例展示了如何通过ByteBuffer包装整数值后经由FileChannel将其同步至磁盘以及逆向的过程,这尤其适用于大规模批量数据交换场景。

总之,无论是传统Java IO还是现代高效的NIO机制都全面地支持了整型数据在各类应用环境中的灵活运用及可靠储存,使得开发者能够轻松应对各种涉及数字内容交互的问题。