我也跟着教程這裏: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();
}
}
}
我知道在哪裏創建文件,因爲我可以看到它創建的文件,但它不與任何文本填充它。
你看着好score.txt文件?嘗試sysout scoreFile.getAbsolutePath()以確保。如果這不能解決你的問題發佈SSCCE(http://sscce.org) – 2012-03-08 18:22:47
爲什麼你採取contentBytes並簡單地扔掉它? – gawicks 2012-03-09 10:49:01