[英]code in try / catch blocks not executing
我是Java初学者,并且正在学习Oracle的Java Tutorials 。
在“ 数据流 ”页面上,使用页面中的示例(如下),我无法执行代码。
更新档案
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
块中的代码未执行。
它可以正常编译,但是当我运行它时,输出仅为:
您的总数是0.000000。
它不会将数据写入另一个保持为空的文件,也不会写入价格,单位和描述。
它还不会写入错误消息。
我的代码有什么问题??
任何答案将不胜感激。
编辑
不使用out.close()
使用后out
是我的失误。 感谢您的回答!
使用out.close()
必须使用out.close()
强制刷新,然后再使用in
变量将其关闭。
编辑:(从我的评论中复制)
由于BufferedInputStream
造成的BufferedInputStream
在关闭文件时创建该文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.