簡體   English   中英

讀寫文件到Android

[英]Reading and writing to the file Android

我正在學習Android,正在制作一些基本的數學程序(游戲)。 它有兩個隨機數,隨機運算符和30秒來盡可能多地解決數學問題。 如果您解決問題,您將獲得1分。

無論如何,現在,我想獲取用戶提出的要點數,並將其寫入文件,然后再讀取(目前僅用於記錄)。

當我單擊按鈕寫入文件時,它確實得到了以下日志消息:09-21 21:11:45.424:DEBUG / Writing(778):這正在寫入日志:2

是的,似乎是這樣寫的。 Okey,讓我們讀一下。

09-21 21:11:56.134:調試/讀取日志(778):這是讀取日志:2

它讀取它。

但是,當我再次嘗試寫入時,似乎它將覆蓋先前的數據。

09-21 21:17:19.183:DEBUG / Writing(778):這是寫日志:1 09-21 21:17:28.334:DEBUG / Reading log(778):這是讀日志:1

如您所見,它僅讀取最后一個輸入。

這是代碼的一部分,我正在編寫和閱讀它。

public void zapisi() {
    // WRITING
    String eol = System.getProperty("line.separator");
    try {
        FileOutputStream fOut = openFileOutput("samplefile.txt",
                MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fOut);

        osw.write(poenibrojanje+eol);
        //for(int i=0;i<10;i++){
        Log.d("Writing","This is writing log: "+poenibrojanje);
        //}

        //osw.flush();
        osw.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


private void citaj() {

    // READING

    String eol = System.getProperty("line.separator");
    try {
        BufferedReader input = new BufferedReader(new InputStreamReader(
                openFileInput("samplefile.txt")));
        String line;
        StringBuffer buffer = new StringBuffer();
        while ((line = input.readLine()) != null) {
            buffer.append(line + eol);
        }
        //TextView textView = (TextView) findViewById(R.id.result);
        Log.d("Reading log","This is reading log:"+buffer);
        System.out.println(buffer);
        //tvRezultat.setText(buffer.toString());

    } catch (Exception e) {
        e.printStackTrace();
    }

}

您可以使用openFileOutput(“ samplefile.txt”,MODE_APPEND)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM