The file is being created successfully, but I cannot get PrintWriter to print an开发者_高级运维ything 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.
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()
You need to close the PrintWriter before the program exits which has the effect of flushing the print stream to ensure everything is written to the file. Try this:
PrintWriter out = null;
try {
//...
out = new PrintWriter(file);
//...
} finally {
if (out != null) {
out.close();
}
}
u need to flush and close the file once done writing http://download.oracle.com/javase/1.4.2/docs/api/java/io/PrintWriter.html void close() Close the stream. void flush() Flush the stream.
printwriter class works with streams not with files, that is why you can not write to that file. you need to create a file by using FileOutputStream, after that you will be able to use printwriter in order to write to that file. Try this:
FileOutputStream exam = new FileOutputStream("ExamScores.txt"); PrintWriter out = new PrintWriter(exam, true);
精彩评论