开发者

How to update txt file in android app?

I'm beginner in Java Android developing. I'm using Eclipse SDK 3.6.1 version. I'm trying to create a txt file and write a date/time and string. But I can't update txt file, I see only one row. There is my code:

@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开发者_如何学C 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();   
    }
}

I use Context.MODE_APPEND, but still can't update txt file. I see only one row.


 rodyk.setText(line);

This code won't append the line you read to the text already in that TextView. It will change the text to the most recent line you read. Hence you should only see the contents of the last line of file.txt in your TextView.

Also whenever you reinstall the application (as you may do a lot during its creation and testing) your file.txt may be getting replaced by a new file.


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

You can write without the Context Like this:

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

It works.


Don't use text view; use Edit Text in your code.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜