[英]How can I save java all lines from java console output to a text file and properly append it?
[英]How to append java output to text file?
当我在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();
}
}
PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt"));
每次到达该行时,它都会删除文件,打开一个新文件,并仅添加当前行。 在循环之前编写此行,然后在循环中将其他代码保持不变。
要附加输出/文本文件,您必须使用另一种编写方式。
我还建议使用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');
}
您不必手动冲洗/关闭它们
您的代码中还有一些小故障。 由于您需要使用try / resource-construct来管理扫描仪和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
}
上面的代码还允许您摆脱main()
方法签名中令人讨厌的throws IOException
。 取而代之的是,现在有两个异常处理程序的漂亮框架(两个catch块),您可以在其中放置一些逻辑,以防万一
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.