PrintWriter无法打印到文件 [英] PrintWriter failing to print to file
本文介绍了PrintWriter无法打印到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
文件正在成功创建,但我无法让PrintWriter将任何内容打印到文本文件中。代码:
The file is being created successfully, but I cannot get PrintWriter to print anything to the text file. Code:
import java.io.File;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
public class exams {
public static void main (String[] args) throws IOException{
Scanner scanner = new Scanner(System.in);
System.out.println("How many scores were there?");
int numScores = scanner.nextInt();
int arr[] = new int[numScores];
for (int x=0; x<numScores; x++){
System.out.println("Enter score #" + (x+1));
arr[x] = scanner.nextInt();
}
File file = new File("ExamScores.txt");
if(!file.exists()){
file.createNewFile();
PrintWriter out = new PrintWriter(file);
for (int y=0; y<arr.length; y++){
out.println(arr[y]);
}
}
else {
System.out.println("The file ExamScores.txt already exists.");
}
}
}
推荐答案
您必须刷新和/或关闭文件才能将数据写入磁盘。
You have to flush and / or close the file to get the data written to the disk.
添加 out.close()
在您的代码中:
PrintWriter out = new PrintWriter(file);
for (int y=0; y<arr.length; y++){
out.println(arr[y]);
}
out.close()
这篇关于PrintWriter无法打印到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文