我正在编写一个程序来读取文本文件中的数据(成绩),计算平均值,然后将每个等级和数据分成两类:好的和差的(取决于低于还是高于平均值)< / p>
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream ("scores.txt");
Scanner read = new Scanner (fis);
int count=0, id;
double total=0,average, grade;
String line;
Scanner stringScanner;
while(read.hasNextLine()){
line = read.nextLine();
stringScanner = new Scanner(line);
id = stringScanner.nextInt();
while (stringScanner.hasNextDouble()){
total = total + stringScanner.nextDouble();
count++;
}
stringScanner.close();
}
average = total/count;
System.out.println("The average is : "+ average);
read.close();
fis = new FileInputStream ("scores.txt");
read = new Scanner (fis);
while(read.hasNextLine()){
line=read.nextLine();
stringScanner=new Scanner (line);
id = stringScanner.nextInt();
while (stringScanner.hasNextDouble()){
grade = stringScanner.nextDouble();
if(grade >= average){
FileOutputStream fos = new FileOutputStream("good.txt");
PrintWriter pr = new PrintWriter (fos);
pr.print(id + "/t"+ grade);
pr.println();
}
else if (grade<average){
FileOutputStream fos = new FileOutputStream("poor.txt");
PrintWriter pr = new PrintWriter (fos);
pr.print(id + "/t"+ grade);
pr.println();
}
else System.out.println("test");
}
stringScanner.close();
}
fis.close();
read.close();
System.out.println("Files have been created...");
}
我认为我在计算平均值方面做得很好(因为它正确输出)。但是,我在编写好的和好的文本文件时遇到了麻烦,这些文件被创建但它们仍然是空的。如何让程序写入两个文件以及我的代码中究竟缺少什么? 谢谢。
编辑: 以下是.txt文件的外观:
206527 44.24
208530 75.38
207135 85.61
205241 91.51
204324 50.61
203357 68.28
202117 57.11
答案 0 :(得分:0)
简而言之:发生这种情况是因为您未在close()
上致电PrintWriter
。除此之外,如果你每次想要添加内容时都不打开文件,它显然会更有效。在开头打开两个文件,然后写入它们。完成工作后,请记得关闭所有已打开的内容。以下是您的计划的第二部分:
fis = new FileInputStream("scores.txt");
read = new Scanner(fis);
FileOutputStream fosGood = new FileOutputStream("good.txt");
PrintWriter prGood = new PrintWriter(fosGood);
FileOutputStream fosPoor = new FileOutputStream("poor.txt");
PrintWriter prPoor = new PrintWriter(fosPoor);
while (read.hasNextLine()) {
line = read.nextLine();
stringScanner = new Scanner(line);
id = stringScanner.nextInt();
while (stringScanner.hasNextDouble()) {
grade = stringScanner.nextDouble();
if (grade >= average)
prGood.println(id + "\t" + grade);
else if (grade < average)
prPoor.println(id + "\t" + grade);
else System.out.println("test");
}
stringScanner.close();
}
prGood.close();
prPoor.close();
fis.close();
fosGood.close();
fosPoor.close();
read.close();
System.out.println("Files have been created...");
此外,您不应该从main
方法中抛出任何异常,而应将代码置于try/catch/finally
块中。在这种情况下,关于关闭文件的所有代码都会进入finally
。您可以选择使用try-with-resources statement。