我是一名初学java程序员,我正在关注Oracle's Java Tutorials。try/catch块中的代码未执行
在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
块不执行,因为某些原因。
会正常编译,但是当我运行它,输出仅为:
你总为0.000000。
它不会将数据写入另一个文件,该文件保持为空,并且它不写入价格,单位和描述。
它也不会写入错误消息。
我的代码有什么问题?
任何答案将不胜感激。
使用out
是我的失误后
不使用out.close()
编辑。感谢您的答案!
相反System.err.println()来的'缓冲的文件被创建,''做e.printStackTrace() ;'看到错误信息... – jlordo