2011-04-16 69 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);