本文目录导读:

我来详细介绍Java数据流(Data Stream)的读写案例,包括基本概念和实际应用示例。
数据流概述
数据流(DataInputStream/DataOutputStream)支持基本数据类型的读写,可以按Java原始数据类型读写数据。
基础读写案例
写入数据到文件
import java.io.*;
public class DataOutputStreamExample {
public static void main(String[] args) {
String filePath = "data.bin";
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream(filePath))) {
// 写入各种基本数据类型
dos.writeInt(100); // 写入整数
dos.writeDouble(3.14159); // 写入双精度浮点数
dos.writeBoolean(true); // 写入布尔值
dos.writeUTF("Hello World"); // 写入字符串(UTF-8格式)
dos.writeLong(123456789L); // 写入长整数
dos.writeFloat(2.71828f); // 写入浮点数
dos.writeChar('A'); // 写入字符
System.out.println("数据写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
从文件读取数据
import java.io.*;
public class DataInputStreamExample {
public static void main(String[] args) {
String filePath = "data.bin";
try (DataInputStream dis = new DataInputStream(
new FileInputStream(filePath))) {
// 按照写入顺序读取数据
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
boolean boolValue = dis.readBoolean();
String strValue = dis.readUTF();
long longValue = dis.readLong();
float floatValue = dis.readFloat();
char charValue = dis.readChar();
// 打印读取的数据
System.out.println("整数: " + intValue);
System.out.println("双精度: " + doubleValue);
System.out.println("布尔值: " + boolValue);
System.out.println("字符串: " + strValue);
System.out.println("长整数: " + longValue);
System.out.println("浮点数: " + floatValue);
System.out.println("字符: " + charValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
实用案例:学生信息管理系统
学生类定义
import java.io.Serializable;
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
private double score;
public Student(int id, String name, int age, double score) {
this.id = id;
this.name = name;
this.age = age;
this.score = score;
}
// Getters and Setters
public int getId() { return id; }
public String getName() { return name; }
public int getAge() { return age; }
public double getScore() { return score; }
@Override
public String toString() {
return String.format("学生ID: %d, 姓名: %s, 年龄: %d, 成绩: %.2f",
id, name, age, score);
}
}
读写学生数据
import java.io.*;
import java.util.*;
public class StudentDataManager {
// 写入学生数据
public static void writeStudents(String fileName, List<Student> students)
throws IOException {
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream(fileName))) {
// 先写入学生数量
dos.writeInt(students.size());
// 遍历写入每个学生信息
for (Student student : students) {
dos.writeInt(student.getId());
dos.writeUTF(student.getName());
dos.writeInt(student.getAge());
dos.writeDouble(student.getScore());
}
System.out.println("成功写入 " + students.size() + " 个学生数据");
}
}
// 读取学生数据
public static List<Student> readStudents(String fileName)
throws IOException {
List<Student> students = new ArrayList<>();
try (DataInputStream dis = new DataInputStream(
new FileInputStream(fileName))) {
// 先读取学生数量
int count = dis.readInt();
// 循环读取每个学生信息
for (int i = 0; i < count; i++) {
int id = dis.readInt();
String name = dis.readUTF();
int age = dis.readInt();
double score = dis.readDouble();
students.add(new Student(id, name, age, score));
}
System.out.println("成功读取 " + students.size() + " 个学生数据");
}
return students;
}
// 测试方法
public static void main(String[] args) {
try {
// 创建学生数据
List<Student> students = Arrays.asList(
new Student(1, "张三", 20, 85.5),
new Student(2, "李四", 21, 92.0),
new Student(3, "王五", 19, 78.5),
new Student(4, "赵六", 22, 95.5)
);
String fileName = "students.dat";
// 写入数据
writeStudents(fileName, students);
// 读取数据
List<Student> loadedStudents = readStudents(fileName);
// 显示读取的数据
System.out.println("\n读取的学生信息:");
for (Student student : loadedStudents) {
System.out.println(student);
}
} catch (IOException e) {
System.err.println("文件操作失败: " + e.getMessage());
e.printStackTrace();
}
}
}
网络数据流传输案例
服务端代码
import java.io.*;
import java.net.*;
public class DataServer {
private static final int PORT = 8888;
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("服务器启动,等待连接...");
while (true) {
try (Socket socket = serverSocket.accept();
DataInputStream dis = new DataInputStream(
socket.getInputStream());
DataOutputStream dos = new DataOutputStream(
socket.getOutputStream())) {
System.out.println("客户端连接: " + socket.getInetAddress());
// 接收客户端数据
int number1 = dis.readInt();
int number2 = dis.readInt();
String operation = dis.readUTF();
System.out.println("收到运算请求: " + number1 + " "
+ operation + " " + number2);
// 执行运算
double result = 0;
switch (operation) {
case "+": result = number1 + number2; break;
case "-": result = number1 - number2; break;
case "*": result = number1 * number2; break;
case "/": result = (double) number1 / number2; break;
default: throw new IllegalArgumentException("不支持的运算");
}
// 发送结果
dos.writeDouble(result);
dos.flush();
System.out.println("计算结果: " + result);
} catch (IOException e) {
System.err.println("处理客户端请求失败: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("服务器启动失败: " + e.getMessage());
}
}
}
客户端代码
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class DataClient {
private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 8888;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_HOST, SERVER_PORT);
DataOutputStream dos = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(
socket.getInputStream());
Scanner scanner = new Scanner(System.in)) {
System.out.println("连接到服务器: " + SERVER_HOST + ":" + SERVER_PORT);
// 获取用户输入
System.out.print("请输入第一个数字: ");
int number1 = scanner.nextInt();
System.out.print("请输入第二个数字: ");
int number2 = scanner.nextInt();
System.out.print("请输入运算符(+,-,*,/): ");
String operation = scanner.next();
// 发送数据到服务器
dos.writeInt(number1);
dos.writeInt(number2);
dos.writeUTF(operation);
dos.flush();
// 接收服务器返回的结果
double result = dis.readDouble();
System.out.println("\n运算结果: " + number1 + " " + operation
+ " " + number2 + " = " + result);
} catch (IOException e) {
System.err.println("客户端连接失败: " + e.getMessage());
}
}
}
重要注意事项
数据类型一致性
// 重要:读写顺序必须一致!
// 写入顺序
dos.writeInt(100);
dos.writeUTF("Hello");
// 读取顺序必须相同
int value = dis.readInt(); // 先读int
String str = dis.readUTF(); // 后读String
异常处理
try (DataInputStream dis = new DataInputStream(
new FileInputStream("data.bin"))) {
// 读取数据前检查是否还有数据
while (dis.available() > 0) {
// 执行读取操作
}
} catch (EOFException e) {
System.out.println("文件读取完毕");
} catch (IOException e) {
System.err.println("IO错误: " + e.getMessage());
}
缓冲区刷新
DataOutputStream dos = new DataOutputStream(
new FileOutputStream("data.bin"));
dos.writeInt(100);
dos.flush(); // 强制将缓冲区的数据写入目标
// 或者在try-with-resources中自动关闭
try (DataOutputStream dos = new DataOutputStream(...)) {
// 写入操作
// 自动调用close()方法,close()会先调用flush()
}
这些案例涵盖了数据流的主要应用场景,包括文件读写、网络传输等,在实际开发中,根据具体需求选择合适的操作方式。