简体   繁体   English

如何从文本文件中读取数据,然后用新数据覆盖它?

[英]How to read data from text file then overwrite it with new data?

I'm new to android studio and I have this textview which shows the data that is stored to my text file. 我是android studio的新手,我有这个textview,它显示了存储到我的文本文件中的数据。 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. 但是,当我返回在文本文件中显示带有新数据的textView的活动时,它不会更改。

Here's the code for my textView 这是我的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();
        }

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);
}

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. 我正在使用Android Studio 1.5.1,并在手机上运行该应用程序。

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! 非常感谢!

This might be due to a FileNotFoundException when you'd read the file in the save method. 当您在save方法中读取文件时,这可能是由于FileNotFoundException引起的。 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. 当您尝试更新文件并将其写入时,您不会分离try/catch方法,因此阅读部分可能会出现异常,从而阻止继续执行脚本和更新文件。 Maybe this was printing in the Logcat but you haven't take a look. 也许这是在Logcat中打印的,但您没有看。
So I'd suggest you to check if the file already exists and to separate the reading/writing parts. 因此,建议您检查文件是否已存在,并分开读取/写入部分。

When you first read the file to display it in TextView , just check if it's created to avoid a background exception: 初次读取文件以在TextView显示该文件时,只需检查是否已创建该文件即可避免后台异常:

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

You can see here where the file should be stored (in getFilesDir() ). 您可以在此处看到文件的存储位置(在getFilesDir() )。 The path is choosen by default when you use openFileInput(String) , and it's: 当您使用openFileInput(String) ,默认情况下会选择该路径,它是:

data/data/com.package.name/files/ 数据/数据/com.package.name/文件/

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. 您必须记住,实际上并没有在代码中创建/files夹,例如,我必须自己创建它才能使用上述方法。 (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());
    }
}

Obviously, this method is called only if the previous check returns true . 显然,仅当先前的检查返回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. 单击“ Button时,您必须执行相同的操作:检查它是否存在->是,获取内容,处理您的东西(添加,加和等)并写入->如果不存在,则只需写入它。
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());
     }
}

At this point, when you returned to the previous activity, you should be able to see the changes. 此时,当您返回上一个活动时,您应该能够看到更改。

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 . 但是,要查看存储中的文件,很遗憾,您必须拥有一个已root用户的设备,否则您将看到一个空文件夹 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() . 您应该完成一个编辑,这将返回到上一个,您只需要在onResume()调用readFile() onResume()而不是onCreate() It will update the new content into the TextView . 它将新内容更新到TextView

Have you tried on updating textview before starting new Activity? 在开始新的活动之前,您是否尝试过更新textview? Example: 例:

txt_start.setText(""+totalStars);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM