为什么BufferedWriter写方法会产生不同的结果?

时间:2011-11-18 21:22:26

标签: java

我不明白为什么这两个实现产生不同的结果?

预期结果的方法:

    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 );
    }
}

数据文件结果

jim,1,112,246

迈克,3,12,24

jim,4,50,100

joni,5,40,80

意外结果的方法:

    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 );
    }
}

数据文件结果

乔,乔,@,

fred ,, {,ö

为什么将out.write语句分成不同的行会导致输出产生奇怪的结果?每个方法都传递一个带有object的数组引用,该对象将结果存储为字符串,short,short短数据类型。

1 个答案:

答案 0 :(得分:6)

我认为log.typelog.durationlog.caloriesburned的值为int,这意味着您正在调用BufferedWriter.write(int)重载。那只是写一个字符。我怀疑你只需要:

out.write(log.name.toString());
out.write(", ");
out.write(String.valueOf(log.type));
out.write(",");
out.write(String.valueOf(log.duration));
out.write(",");
out.write(String.valueOf(log.caloriesburned));
out.write("\n");

请注意,您应该在finally块中关闭编写器,以便即使出现异常也会关闭它。