我在这里按照教程:http ://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
并已实现以下代码作为示例:
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();
}
}
}
我知道文件是在哪里创建的,因为我可以看到它创建了文件,但它没有用任何文本填充它。