2011-04-16 37 views
9

文件正在成功创建,但我无法让PrintWriter将任何内容打印到文本文件中。代码: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."); 
     } 
    } 
} 

回答

19

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

在你的代码添加out.close()

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

谢谢!我知道这是一件小事。 – tim 2011-04-16 20:15:40

3

您需要具有冲洗打印流,以确保一切都被写入文件的效果在程序退出之前关闭的PrintWriter。试试这个:

PrintWriter out = null; 
try { 
    //... 
    out = new PrintWriter(file); 
    //... 
} finally { 
    if (out != null) { 
     out.close(); 
    } 
} 
0

printwriter类与不与文件的流一起工作,这就是为什么你不能写入该文件。您需要使用FileOutputStream创建一个文件,然后您将能够使用printwriter来写入该文件。试试这个:

FileOutputStream exam = new FileOutputStream(“ExamScores.txt”); PrintWriter out = new PrintWriter(exam,true);