繁体   English   中英

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

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

我是android studio的新手,我有这个textview,它显示了存储到我的文本文件中的数据。 如果单击按钮,它将读取文本文件中的数据,添加整数,并且总和应替换文本文件中的现有数据。 但是,当我返回在文本文件中显示带有新数据的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();
        }

以及按钮的代码

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

我的清单文件中有这个。

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

我应该做些什么来定位和创建文本文件?

我已经被困在这里好几天了。 请帮我。 非常感谢!

当您在save方法中读取文件时,这可能是由于FileNotFoundException引起的。 当您尝试更新文件并将其写入时,您不会分离try/catch方法,因此阅读部分可能会出现异常,从而阻止继续执行脚本和更新文件。 也许这是在Logcat中打印的,但您没有看。
因此,建议您检查文件是否已存在,并分开读取/写入部分。

初次读取文件以在TextView显示该文件时,只需检查是否已创建该文件即可避免后台异常:

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

您可以在此处看到文件的存储位置(在getFilesDir() )。 当您使用openFileInput(String) ,默认情况下会选择该路径,它是:

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

您必须记住,实际上并没有在代码中创建/files夹,例如,我必须自己创建它才能使用上述方法。 (这只能是我的设备,但是您会意识到这会阻止文件的创建。)

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

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

显然,仅当先前的检查返回true才调用此方法。 单击“ Button时,您必须执行相同的操作:检查它是否存在->是,获取内容,处理您的东西(添加,加和等)并写入->如果不存在,则只需写入它。
可以进行以下操作:

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

此时,当您返回上一个活动时,您应该能够看到更改。

但是,要查看存储中的文件,很遗憾,您必须拥有一个已root用户的设备,否则您将看到一个空文件夹 最后,您将避免重新启动活动。 您应该完成一个编辑,这将返回到上一个,您只需要在onResume()调用readFile() onResume()而不是onCreate() 它将新内容更新到TextView

在开始新的活动之前,您是否尝试过更新textview? 例:

txt_start.setText(""+totalStars);

暂无
暂无

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

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