如何读取文本文件中的数据,然后用新的数据覆盖它吗? [英] How to read data from text file then overwrite it with new data?

查看:332
本文介绍了如何读取文本文件中的数据,然后用新的数据覆盖它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Andr​​oid工作室,我有这样的TextView这表明存储到我的文本文件中的数据。如果我按一下按钮,就应该阅读文本文件中的数据,添加整数,总数应在文本文件替换现有的数据。然而,当我回到其显示的TextView的与在文本文件中的新的数据的活动,它不会改变。

I'm new to android studio and I have this textview which shows the data that is stored to my text file. If I click the button, it should read the data inside the text file, add integer and the sum should replace the existing data in the text file. However when I return to the activity which show's the textView with the new data in the text file, it does not change.

这里的code为我的TextView

Here's the code for my textView

        txt_stars = (TextView) findViewById(R.id.txtStars);

        try {
            FileInputStream fileInputStream = openFileInput("Stars.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String star;
            while ((star=bufferedReader.readLine()) != null){
                stringBuffer.append(star);
            }
            txt_stars.setText(stringBuffer.toString());
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

而code的按钮

And the code for the button

Integer stars, totalStars;


public void onClick(DialogInterface dialog, int whichButton) {

  try {
    FileInputStream fileInputStream = openFileInput("Stars.txt");
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuffer stringBuffer = new StringBuffer();
    String star;
    while ((star = bufferedReader.readLine()) != null) {
      stringBuffer.append(star);
    }
    stars = Integer.parseInt(stringBuffer.toString());
    totalStars = stars + 50;
    //is this acceptable?
    FileOutputStream fileOutputStream = openFileOutput("Stars.txt", MODE_PRIVATE);
    fileOutputStream.write(totalStars.toString().getBytes());
    fileOutputStream.close();

  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }

  Intent nextForm = new Intent(".MainActivity");
  startActivity(nextForm);
}

和也,在哪里可以找到我的手机上创建的文本文件,这样我可以向文本文件被创建?我使用的是Android 1.5.1工作室和运行应用程序到我的手机。

And also, where can I find the created text file in my phone so that I can assure that the text file is created? I'm using Android studio 1.5.1 and running the app to my phone.

我有这在我的清单文件。

I have this in my manifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

有什么我应该做的定位和创建文本文件?

Is there anything I should do to locate and create the text file?

我一直困在这里天。请帮帮我。
非常感谢!

I have been stuck here for days. Please help me. Thanks a lot!

推荐答案

这可能是由于 FileNotFoundException异常当你读取保存方法的文件。当您尝试更新的文件,并写入到它,你不分离的try / catch 方法,所以你可能在这prevents阅读部分的异常继续该脚本并更新该文件。也许这是在logcat的打印,但你有没有去看看。结果
所以,我建议你检查,如果该文件已经存在,并读/写部分分开。

This might be due to a FileNotFoundException when you'd read the file in the save method. When you try to update the file and write into it, you don't separate the try/catch methods so you might have an exception at the reading part which prevents to continue the script and to update the file. Maybe this was printing in the Logcat but you haven't take a look.
So I'd suggest you to check if the file already exists and to separate the reading/writing parts.

当你第一次读的TextView 来显示它,只是检查,如果它的创建,以避免背景异常文件:

When you first read the file to display it in TextView, just check if it's created to avoid a background exception:

File f = new File(getFilesDir().toString() + "/stars.txt");
Log.v("", "Does the file exist? " + f.exists()); 
if (f.exists()) {
    readFile();
}

您可以在这里看到该文件应存放(在 getFilesDir())。路径默认情况下choosen当您使用 openFileInput(字符串),它是:

You can see here where the file should be stored (in getFilesDir()). The path is choosen by default when you use openFileInput(String), and it's:

数据/数据​​/ com.package.name /文件/

data/data/com.package.name/files/

您必须记住,你其实并不创建 /文件文件夹中code和例如,我不得不创建它自己的工作用上述方法。 (这可能只是我的设备,但是你会意识到这可能prevent要创建的文件。)

You have to keep in mind that you actually don't create /files folder in your code and for example, I had to create it myself to work with the above method. (This can be only my device but you'd be aware this can prevent the file to be created.)

现在,有一个在您的阅读方法没有大的变化,这是它的外观:

Now, there is no big changes in your reading method and this is how it looks:

private void readFile() {
    try {
        FileInputStream file = openFileInput("stars.txt");
        InputStreamReader inRead = new InputStreamReader(file);
        BufferedReader buffReader = new BufferedReader(inRead);

        StringBuffer stringBuffer = new StringBuffer();
        String star;

        while ((star = buffReader.readLine()) != null) {
            stringBuffer.append(star);
        }

        inRead.close();
        file.close();

        txt_stars.setText(stringBuffer.toString());
    } catch (Exception e) {
        Log.e("ReadFile", e.toString());
    }
}

显然,这种方法被称为只有previous检查返回真正。你必须做同样的按钮被点击:检查它是否存在 - >如果是,获取内容,做你的东西(添加,总和,等等)和write进去 - >如果没有,只是通过写来创建它结果
东西如下将工作:

Obviously, this method is called only if the previous check returns true. You have to do the same when the Button is clicked: check if it exists -> if yes, get the content, do your stuff (add, sum, etc) and write into it -> if not, just create it by writing into it.
Something as follows will work:

public void writeFile(View v) {
    File f = new File(getFilesDir().toString() + "/stars.txt");
    Log.v("", "Does it exist? " + f.exists());
    String result = "";

    if ( f.exists() ) {
       try {
            FileInputStream file = openFileInput("stars.txt");
            InputStreamReader inRead = new InputStreamReader(file);
            BufferedReader buffReader = new BufferedReader(inRead);
            StringBuffer stringBuffer = new StringBuffer();

            String star;

            while ((star=buffReader.readLine()) != null) {
                stringBuffer.append(star);
            }

            result = stringBuffer.toString();
            inRead.close();
            file.close(); 
        } catch (Exception e) {
            Log.e("WriteFile", "--- Error on reading file: "+e.toString());
        }
    } else {
        // get the user's star or whatever
        result = editRating.getText().toString();
    }

    Log.v("WriteFile", "--- Read file returns: " + result);
    stars = Integer.parseInt(result);
    totalStars = stars + 50;

    try {         
        FileOutputStream fileOut = openFileOutput("stars.txt", MODE_PRIVATE);
        OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
        outputWriter.write(String.valueOf(totalStars));
        outputWriter.close();
        fileOut.close();

        // display file saved message
        Toast.makeText(getBaseContext(), "File saved", Toast.LENGTH_SHORT).show();
     } catch (Exception e) {
         Log.e(" WriteFile", e.toString());
     }
}

在这一点上,当你回到previous活动,你应该能够看到的变化。

At this point, when you returned to the previous activity, you should be able to see the changes.

不过,为了看到您的存储文件,你不幸必须有一个根深蒂固的设备,否则<一个href=\"http://stackoverflow.com/questions/4926027/what-file-system-path-is-used-by-androids-context-openfileoutput#comment38527714_16849318\">you'll看到一个空文件夹。最后,您会避免重新启动该活动。你应该完成的编辑之一,这会回来的previous一个,你只需要调用 ReadFile的() onResume( )而不是的onCreate()。它会更新新的内容到的TextView

However, in order to see the file in your storage, you unfortunately must to have a rooted device, else you'll see an empty folder. Then finally, you'd avoid to restart the Activity. You should finish the editing one, this will come back to the previous one, and you just have to call readFile() in onResume() instead of onCreate(). It will update the new content into the TextView.

这篇关于如何读取文本文件中的数据,然后用新的数据覆盖它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆