如何将java输出附加到文本文件?

时间:2016-01-17 09:11:38

标签: java

当我在Java控制台中打印出来时,下面的程序工作得很好但是当我尝试将程序附加到文本文件中时,它只会将学生平均值的1/5打印到附加文本文件中

 Bobby, average = 93

我希望它能打印所有5个学生的平均值

 Agnes, average = 76
 Bufford, average = 91
 Julie, average = 94
 Alice, average = 39
 Bobby, average = 93

提前致谢。

 import java.util.*;
 import java.io.*;
 public class StudentAverage {
 public static void main(String[]args) throws IOException {


 Scanner scanner = new Scanner(new        
 File("D:\\School\\StudentGrades.txt"));

 while (scanner.hasNextLine()) {

    Scanner scanners = new Scanner(scanner.nextLine());

    String name = scanners.next(); 
    double total = 0;
    int num = 0;

    while (scanners.hasNextInt()) { 
        total += scanners.nextInt();
        num++;
    }

    PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt"));
    output.print(name + ", average = " + (Math.round(total/num)));
    output.flush();
}
scanner.close();
}
}

3 个答案:

答案 0 :(得分:3)

PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt"));

每次到达此行时,它都会删除该文件,打开一个新文件并仅添加当前行。在循环之前写这一行,并在循环中只保留其他代码。

答案 1 :(得分:0)

要附加输出/文本文件,您必须使用不同的编写方式。

我还建议使用try-with-resource块来避免记忆泄漏。

try (OutputStream output = new FileOutputStream("myFile.txt", true);
        Writer writer = new OutputStreamWriter(output)) {
    writer.write(name + ", average = " + (Math.round(total / num)) + '\n');
}

您不必手动冲洗/关闭它们

答案 2 :(得分:0)

您的代码中还有一些故障。由于您需要使用try / resource-construct管理Scanner和PrintWriter,我更喜欢将输入和输出例程分开,并将文件的相关内容临时读入内存。

这是一个想法:

LinkedHashMap<String, Integer> students = new LinkedHashMap<>();

// Input routine
try (Scanner scanner = new Scanner(new File("D:\\School\\StudentGrades.txt"))) {
    while (scanner.hasNextLine()) {
        try (Scanner scanners = new Scanner(scanner.nextLine())) {
            String name = scanners.next(); 
            int total = 0;
            int num = 0;

            while (scanners.hasNextInt()) { 
                total += scanners.nextInt();
                num++;
            }

            students.put(name, (int) Math.round((double)total/num));
        }       
    }
}
catch (FileNotFoundException e) {
    // do something smart
}

// Output routine
try (PrintStream output = new PrintStream ("D:\\School\\WriteStudentAverages.txt")) {
    for (Entry<String, Integer> student : students.entrySet()) {
        output.println(student.getKey() + ", average = " + Integer.toString(student.getValue()));       
    }
}
catch (FileNotFoundException e) {
    // do something smart
}

以上内容还可以让您摆脱throws IOException - 方法签名中令人讨厌的main()。相反,现在有一个异常处理程序的两个漂亮的骨架(两个catch块),你可以在其中放置一些触发的逻辑

  • 未找到输入文件/无法读取(第一次捕获)
  • 输出文件不可写/无法创建(第二次捕获)