简体   繁体   English

读写文件到Android

[英]Reading and writing to the file Android

I am learning Android and I am making some basic math program(game). 我正在学习Android,正在制作一些基本的数学程序(游戏)。 It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can. 它有两个随机数,随机运算符和30秒来尽可能多地解决数学问题。 If you solve problem u get 1 point. 如果您解决问题,您将获得1分。

Anyway right now, I want to get number of points that user have made, and write it to the file, and later to read it ( for now just to log it). 无论如何,现在,我想获取用户提出的要点数,并将其写入文件,然后再读取(目前仅用于记录)。

When I click to button to write file, it does and I get this log message: 09-21 21:11:45.424: DEBUG/Writing(778): This is writing log: 2 当我单击按钮写入文件时,它确实得到了以下日志消息:09-21 21:11:45.424:DEBUG / Writing(778):这正在写入日志:2

Yeah, seems that it writes. 是的,似乎是这样写的。 Okey, lets read it. Okey,让我们读一下。

09-21 21:11:56.134: DEBUG/Reading log(778): This is reading log:2 09-21 21:11:56.134:调试/读取日志(778):这是读取日志:2

It reads it. 它读取它。

But when I try again to write, it seems that it will overwrite previous data. 但是,当我再次尝试写入时,似乎它将覆盖先前的数据。

09-21 21:17:19.183: DEBUG/Writing(778): This is writing log: 1 09-21 21:17:28.334: DEBUG/Reading log(778): This is reading log:1 09-21 21:17:19.183:DEBUG / Writing(778):这是写日志:1 09-21 21:17:28.334:DEBUG / Reading log(778):这是读日志:1

As you can see it reads just last input. 如您所见,它仅读取最后一个输入。

Here it is that part of code, where I am writing and reading it. 这是代码的一部分,我正在编写和阅读它。

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