2012-03-08 71 views
1

我也跟着教程這裏:http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/Java的FileOutputStream中寫,不是工作

,並實施下列代碼爲例:

File scoreFile = new File("score.txt"); 
if(!scoreFile.exists()) { 
    scoreFile.createNewFile(); 
} 
oFile = new FileOutputStream(scoreFile, false); 
oFile.write("Score = 1".getBytes()); 
oFile.flush(); 
oFile.close(); 

但沒有什麼是被寫入文件score.txt。

編輯:全功能如下:

// Set win or loose to score.dat. 
    public void setScore(boolean won, boolean reset){ 
     out.println("setScore()"); 
     long timePassed = (timeEnd - timeStart)/1000; // Seconds passed. 
     double[] prevScore = getScore(); // get previous score (Won, Lost). 
     // Create a writer to edit the file. 
     File scoreFile = new File("score.txt"); 
     if(!scoreFile.exists()) { 
      try { 
       scoreFile.createNewFile(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     if(!reset){ 
      if(won){ 
       // Add time to Win values. 
       prevScore[0] += timePassed; 
      } 
      else{ 
       // Add time to Lost values. 
       prevScore[1] += timePassed; 
      } 
      try { 
       FileOutputStream oFile = new FileOutputStream(scoreFile, false); 
       // Write new score. 
       byte[] contentBytes = (String.valueOf(prevScore[0]+" "+prevScore[1])).getBytes(); 
       oFile.write("Bye".getBytes()); 
       oFile.flush(); 
       oFile.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
     else{ 
      // If battle ended, delete the scores. 
      FileOutputStream oFile; 
      try { 
       if(!scoreFile.exists()) { 
        scoreFile.createNewFile(); 
       } 
       oFile = new FileOutputStream(scoreFile, false); 
       oFile.write("Error".getBytes()); 
       oFile.flush(); 
       oFile.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

我知道在哪裏創建文件,因爲我可以看到它創建的文件,但它不與任何文本填充它。

+3

你看着好score.txt文件?嘗試sysout scoreFile.getAbsolutePath()以確保。如果這不能解決你的問題發佈SSCCE(http://sscce.org) – 2012-03-08 18:22:47

+0

爲什麼你採取contentBytes並簡單地扔掉它? – gawicks 2012-03-09 10:49:01

回答

2

那段代碼對我來說很有用......你在找對的地方嗎?例如,您可以嘗試將文件名更改爲"C:\\score.txt",以確保您查看正確的文件夾。

+0

你可以看看編輯的問題,並建議任何可能修復代碼?謝謝 – 2012-03-08 20:30:10

1

的代碼肯定能行。(假定您已經聲明OFILE).Score.txt必須在你的工作目錄