I don’t understand why these two implementations produce different results?
Method with expected results:
private void writeToFile(WorkoutLog log){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("src/exercise/textfile2.txt", true));
out.write(log.name.toString() + ", " + log.type + ", " + log.duration + ", " + log.caloriesburned + "\n");
out.close();
}catch (IOException e) {
System.out.println("error writing record to text file " + e );
}
}
data file result
jim, 1, 123, 246
mike, 3, 12, 24
jim, 4, 50, 100
joni, 5, 40, 80
Method with unexpected result:
private void writeToFile2(WorkoutLog log){
try {
BufferedWriter out = new BufferedWriter(new FileWriter("src/exercise/textfile2.txt", true));
out.write(log.name.toString());
out.write(", ");
out.write(log.type);
out.write(",");
out.write(log.duration);
out.write(",");
out.write(log.caloriesburned);
out.write("\n");
out.close();
}catch (IOException e) {
System.out.println("error writing record to text file " + e );
}
}
data file result
joe, , ,@
fred, ,{,ö
Why is breaking the out.write statements onto separate lines causing the output to produce odd results? Each method is being passed an array reference with object that stores the result to write as string, short, short short data types.
I assume that
log.type,log.durationandlog.caloriesburnedareintvalues, which means you’re calling theBufferedWriter.write(int)overload. That just writes a single character. I suspect you just need:Note that you should close the writer in a
finallyblock so that it gets closed even if there’s an exception.