I'm learning Java from the Oracle documentation and lessons and I got to this part (file I/O, streams, etc) and I have some code here that just doesn't work, and I'm not sure why. I don't get any errors or warnings, nothing, the DataOutputStream
simply won't write to the file.
I tried removing the BufferedOutputStream
and it works that way, so I'm guessing that the problem lies on the Buffered Stream, but I don't know why.
Perhaps something is missing. I'm really stuck.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Principal {
static final String dataFile = "invoicedata.txt";
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) throws IOException {
//DECLARATION
DataOutputStream out = null;
DataInputStream in = null;
try {
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
//WRITING???
for (int i = 0; i < prices.length; i ++) {
out.writeDouble(prices[i]);
out.writeInt(units[i]);
out.writeUTF(descs[i]);
}
} catch (Exception e) {
System.err.println("ERROR!");
e.printStackTrace();
}
double price;
int unit;
String desc;
double total = 0.0;
//READING
try {
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 (EOFException e) {
System.err.println("END OF FILE!");
}
}
}