文本文件无法正确写入和存​​储数据

时间:2011-05-30 16:05:52

标签: android file read-write

我在创建和编辑文本文件时遇到了一些问题。该文件似乎永远不会存储数据。

  • 我需要创建一个文本文件(如果有的话) 不可用。
  • 如果文件中有数据,请读取该数据并使其可用。
  • 存储的数据是String,包含三个整数值,以,分隔,例如:String finalWrite = "3,5,1"
  • 因此需要拆分此字符串,并将其转换为整数以允许添加新计数器。
  • 需要将这些新计数器写入存储在设备上的文本文件

没有发生错误,也没有强制关闭。

我只能使用Logcat来确定值没有正确存储。

我查看了Android开发网站上的文档。如果有人可以帮助或指出我正确的方向,那将非常感谢!

我正在使用的写方法:

public void WriteItIn() throws IOException
{
    FileOutputStream fOut = openFileOutput("stats.txt", Context.MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    ReadItIn(); //calls the read method, to get the values from the file
    int tmp1 = 0 + countertmp + counter;
    int tmp2 = 0 + counterpostmp + counterpos;
    int tmp3 = 0 + counternegtmp + counterneg;
    finalwrite = "" + tmp1 + "," + tmp2 + "," + tmp3;
    osw.write(finalwrite);
    osw.flush();
    osw.close();
}

Read方法:

public void ReadItIn() throws IOException
            {
                FileInputStream fIn = openFileInput("stats.txt");
                InputStreamReader isr = new InputStreamReader(fIn);
                char[] inputBuffer = new char[fIn.available()];
                isr.read(inputBuffer);
                stringFromFile = new String(inputBuffer);
                String [] tmp = stringFromFile.split("\\,");
                if(tmp.length > 0)
                {
                    Log.d("READ", " NOT NULL");
                    for(int i = 0;i<tmp.length ; i++)
                    {
                        String temper = tmp[i];
                        if(temper == null || temper == "")
                        {
                                Log.d("NULL", "NULLIFIED");
                        }
                        else
                            try
                        {
                            int x = Integer.parseInt(temper, 10);
                            if(i == 0){counter = x;}
                            else if(i == 1){counterpos = x;}
                            else if(i == 2){counterneg = x;}
                        }
                        catch(NumberFormatException e)
                        {
                            e.printStackTrace();
                        }
                    }   
                }
                else
                    Log.d("READ", "NULL");
            }

1 个答案:

答案 0 :(得分:1)

主要问题是,只要您调用openFileOutput,您的 stats.txt 文件就会一次又一次地被删除。

如果您尝试逐步调试代码,您可以看到第一次运行应用程序时,在调用openFileOutput时,文件将以0大小创建。您可以从DDMS文件资源管理器中进行检查。

因此,当你阅读它时,它什么都没有,ReadItIn没有任何内容。当您编写并关闭它时,您可以从DDMS文件资源管理器中看到该文件存在且大小&gt; 0,这是正确的。

但是当你再次通过WriteItIn时,只要你调用openFileOutput,就可以从文件浏览器中看到文件大小恢复为0.

相关问题