Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.");
        }   
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
654 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have to flush and / or close the file to get the data written to the disk.

Add out.close() in your code:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...