【问题标题】:Why is my code not writing to file?为什么我的代码没有写入文件?
【发布时间】:2016-03-13 23:29:48
【问题描述】:

我正在尝试在我的活动开始时从文本文件中读取一个整数。 在我的日志中,我只看到

调试:尝试读取高分文件

永远不会

调试:读取高分文件

调试:无法读取高分文件

为什么我的文件是由 writeHighScore 文件创建的,但没有写入任何值。

public class GameScreen extends AppCompatActivity implements View.OnClickListener {

private Simon simon = new Simon();;
private int score = 0;
private int highScore = 0;
private String highScoreString;
private String FILENAME = "highscore.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_screen);

    //Read highScore file
    TextView highScoreTV = (TextView) findViewById(R.id.high_score_tv);

    Log.i("DEBUG", "Attempt to read High Score File");

    try{
        FileInputStream fis = openFileInput(FILENAME);
        Scanner scanner = new Scanner(fis);
        if(scanner.hasNext()){
            Log.i("DEBUG", "Reading High Score File");
            highScoreString = scanner.nextLine();
            highScore = Integer.getInteger(highScoreString);
        }
        scanner.close();
    } catch (FileNotFoundException e){
        Log.e("READ ERROR", "Could not read high score: " + e.getMessage());
    }
    highScoreTV.setText(""+highScore);
}

writeHighScore

private void writeHighScore(){
        try {
            FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw);
            Log.i("DEBUG", "Writing High Score File");
            pw.println("" + score + "\n");
        } catch (FileNotFoundException e) {
            Log.e("WRITE ERROR", "Cannot Save: " + e.getMessage());
            e.printStackTrace();
            Toast.makeText(GameScreen.this, "Error Saving", Toast.LENGTH_SHORT).show();
        }
    }

【问题讨论】:

  • 您的文件好像是空的。
  • 写入同一个文件的代码在哪里?
  • 你能告诉我们那个文件里有什么吗?
  • 你想要Integer.parseInt(highScoreString) 而不是Integer.getInteger(highScoreString)getInteger 根据文档用于系统属性
  • 添加了我的 writeHighScore 方法,我检查了我的文件,虽然我收到了日志消息“DEBUG:正在写入高分文件”,但它看起来像是空的所以看来我正在错误地写入文件。该文件确实存在,但它是空的。

标签: java android file file-io fileinputstream


【解决方案1】:

我认为问题是您忘记关闭打印编写器,因此阅读器无法打开文件。

只需在您的 writeHighScore 方法中添加一个结束语句即可解决问题。

【讨论】:

  • 这就是解决方案!这是我第二次处理文件 io,我想我在从旧代码复制时错过了那部分。
猜你喜欢
  • 2020-10-07
  • 2019-11-09
  • 2013-10-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
相关资源
最近更新 更多