小编典典

PrintWriter无法打印到文件

java

文件创建成功,但是我无法让PrintWriter将任何内容打印到文本文件。码:

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

阅读 222

收藏
2020-11-16

共1个答案

小编典典

您必须刷新和/或关闭文件才能将数据写入磁盘。

添加out.close()您的代码:

PrintWriter out = new PrintWriter(file);
for (int y=0; y<arr.length; y++){
    out.println(arr[y]);
}
out.close()
2020-11-16