I'm a beginner java programmer, and I'm following Oracle's Java Tutorials.
On the page on Data Streams, using the example from the page (below), I can't get the code to execute.
Update File
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);
}
}
The code in the try and catch blocks are not executing, for some reason.
It compiles normally, but when I run it, the output is only:
Your total is 0.000000.
It doesn't write the data into the other file, which stays empty, and it doesn't write the prices, units, and descriptions.
It also doesn't write an error message.
What is wrong with my code??
Any answers would be greatly appreciated.
EDIT
not using out.close() after using the out was my mistake. Thanks for the answers!
System.err.println();doe.printStackTrace();to see the error messages...