Как обновить TXT-файл в приложении для Android?

1

Я начинаю разработку 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 файл. Я вижу только одну строку.

  • 0
    Есть ли конкретная причина, по которой вы не используете базу данных для хранения этих временных меток?
  • 0
    нет, я просто ищу лучший способ решить эту проблему. У меня один вопрос: когда я создаю файл file.txt, где я могу его найти?
Теги:
view
input
text-files

3 ответа

3
 rodyk.setText(line);

Этот код не добавит строку, которую вы читаете, к тексту уже в этом TextView. Он изменит текст на самую последнюю прочитанную вами строку. Следовательно, вы должны видеть содержимое последней строки файла .txt в вашем TextView.

Кроме того, всякий раз, когда вы переустанавливаете приложение (как вы можете много сделать во время его создания и тестирования), файл file.txt может быть заменен новым файлом.

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

Вы можете писать без контекста:

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

Он работает.

0

Не использовать текстовое представление; используйте Редактировать текст в своем коде.

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню