[英]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.