【问题标题】:How to update txt file in android app?如何在android应用程序中更新txt文件?
【发布时间】:2011-02-15 13:30:10
【问题描述】:

我是 Java Android 开发的初学者。我正在使用 Eclipse SDK 3.6.1 版本。我正在尝试创建一个 txt 文件并写入日期/时间和字符串。但我无法更新 txt 文件,我只看到一行。有我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logfile);
    working();
    viewing ();
}

public void working() {
    // try to write the content
    try {
        // open myfilename.txt for writing
        FileOutputStream out =
            openFileOutput("file.txt",Context.MODE_APPEND);
        // write the contents on mySettings to the file
        String time = DateFormat.getDateTimeInstance().format(new Date());
        String abs = "action";
        String mySettings = time+" -- "+abs+"\n";
        out.write(mySettings.getBytes());
        // close the file
        out.close();
    } catch (java.io.IOException e) {
        //do something if an IOException occurs.
        e.printStackTrace();
    }
}

public void viewing (){
    TextView rodyk = (TextView)findViewById(R.id.textas);

    try {
        // open the file for reading
        InputStream instream = openFileInput("file.txt");

        // if file the available for reading
        if (instream != null) {
            // prepare the file for reading
            InputStreamReader inputreader = new InputStreamReader(instream);
            BufferedReader buffreader = new BufferedReader(inputreader);

            String line;

            // read every line of the file into the line-variable, on
            // line at the time
            while (( line = buffreader.readLine()) != null) {
                // do something with the settings from the file     
                rodyk.setText(line);
            }
        }

        // close the file again
        instream.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();   
    }
}

我使用 Context.MODE_APPEND,但仍然无法更新 txt 文件。我只看到一排。

【问题讨论】:

  • 您没有使用数据库存储这些时间戳是否有特殊原因?
  • 不,我只是在寻找解决此问题的最佳方法。我有一个问题:当我创建 file.txt 时,我在哪里可以找到它?

标签: android input view text-files


【解决方案1】:
 rodyk.setText(line);

此代码不会将您阅读的行附加到该 TextView 中已有的文本中。它会将文本更改为您阅读的最新行。因此,您应该只能在 TextView 中看到 file.txt 最后一行的内容。

此外,每当您重新安装应用程序时(因为您在创建和测试应用程序期间可能会做很多事情),您的 file.txt 可能会被新文件替换。

【讨论】:

    【解决方案2】:
    FileOutputStream out =
        openFileOutput("file.txt",Context.MODE_APPEND);
    

    你可以在没有上下文的情况下这样写:

    FileOutputStream out =
        openFileOutput("file.txt",MODE_APPEND);
    

    有效。

    【讨论】:

      【解决方案3】:

      不要使用文本视图;在代码中使用编辑文本。

      EditText et=(EditText)findviewbyId(R.id.et);
      ...
      ...
      ...
      et.setText(line);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多