我正在从 Oracle 文档和课程中学习 Java,我到了这一部分(文件 I/O、流等),我这里有一些代码不起作用,我不知道为什么。我没有收到任何错误或警告,什么也没有,DataOutputStream
根本不会写入文件。
我尝试删除它BufferedOutputStream
并且它以这种方式工作,所以我猜测问题出在缓冲流上,但我不知道为什么。
也许缺少了什么。我真的被困住了。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Principal {
static final String dataFile = "invoicedata.txt";
static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 };
static final int[] units = { 12, 8, 13, 29, 50 };
static final String[] descs = {
"Java T-shirt",
"Java Mug",
"Duke Juggling Dolls",
"Java Pin",
"Java Key Chain"
};
public static void main(String[] args) throws IOException {
//DECLARATION
DataOutputStream out = null;
DataInputStream in = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
//WRITING???
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
} catch (Exception e) {
System.err.println("ERROR!");
e.printStackTrace();
}
double price;
int unit;
String desc;
double total = 0.0;
//READING
try {
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d" + " units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch (EOFException e) {
System.err.println("END OF FILE!");
}
}
}