📄 dataioexam.java
字号:
import java.io.*;
public class DataIOExam {
public static void main(String[] args) throws IOException {
//创建数据输出流
DataOutputStream out = new DataOutputStream(new FileOutputStream("my.dat"));
//初始化输出数据
double[] prices = {19.95, 9.90, 15.15, 3.45, 4.37};
int[] units = {12, 8, 13, 26, 50};
String[] products = {"APPLE","PEA","TOMATO","PEACH","BREAD" };
//数据输出
for (int i = 0; i < prices.length; i++) {
out.writeDouble(prices[i]);
out.writeChar('\t');
out.writeInt(units[i]);
out.writeChar('\t');
out.writeBytes(products[i]);
out.writeChar('\n');
}
//关闭数据输出流
out.close();
//创建数据输入流
DataInputStream in = new DataInputStream(new FileInputStream("my.dat"));
double price;
int unit;
String prod;
double total = 0.0;
try {
int i = 0;
//利用数据输入流读文件内容
while (i++<5) { //根据写入内容读取,如果不设置循环条件,将抛出异常
price = in.readDouble();
in.readChar(); // throws out the tab
unit = in.readInt();
in.readChar(); // throws out the tab
prod = in.readLine();
System.out.println("产品:" + prod + "价格:$" + price + " 数量:" + unit);
total = total + unit * price;
}
}
//捕获异常
catch (EOFException e) {
e.printStackTrace();
}
System.out.println("金额合计: $" + total);
//关闭数据输入流
in.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -