我是一名初学者 Java 程序员,我正在关注 Oracle's Java Tutorials .
在Data Streams的页面上,使用页面中的示例(如下),我无法执行代码。
更新文件
import java.io.*;
public class DataStreams {
static final String dataFile = "F://Java//DataStreams//invoicedata.txt"; // used to be non-existent file
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[]) {
try {
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
out.close(); // this was my mistake - didn't have this before
} catch(IOException e){
e.printStackTrace(); // used to be System.err.println();
}
double price;
int unit;
String desc;
double total = 0.0;
try {
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
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(IOException e) {
e.printStackTrace(); // Used to be System.err.println();
}
System.out.format("Your total is %f.%n" , total);
}
}
由于某种原因,try
和 catch
block 中的代码未执行。
它可以正常编译,但是当我运行它时,输出仅为:
Your total is 0.000000.
它不会将数据写入另一个文件,该文件保持为空,并且不会写入价格、单位和说明。
它也不会写入错误消息。
我的代码有什么问题吗?
任何答案将不胜感激。
编辑
在使用out
之后没有使用out.close()
是我的错误。谢谢各位的解答!
最佳答案
在使用 out.close()
强制刷新后,您必须关闭流,然后才能将其与 in
变量重用。
编辑:(从我的评论复制)
由于 BufferedInputStream
关于java - try/catch block 中的代码未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18450628/