如何在打开应用程序时阅读文本文件?

问题描述:

我正在制作一个应用程序,在其中设置了我的学校平衡设置,并且可以按专用按钮根据购买的内容取走一定的金额。我在平衡方面遇到麻烦。我有办法将它更新为我想要的,但是在终止应用程序之后,我希望它在TextView中保持不变。到目前为止,我能够通过视频将它保存到一个文件中,或者至少我希望是我。如何在打开应用程序时阅读文本文件?

我怎么能打开应用程序读取文本文件,并设置TextView等于文件中的内容?

submitBtn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      String submitAmount = amountEnter.getText().toString(); 
      balance.setText(submitAmount); 

      String myBalance = balance.getText().toString(); 

      try { 
       FileOutputStream fou = openFileOutput("balance.txt", 
MODE_WORLD_READABLE); 
       OutputStreamWriter osw = new OutputStreamWriter(fou); 
       try { 

        osw.write(myBalance); 
        osw.flush(); 
        osw.close(); 

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

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

     } 
    }); 
+1

得到它你可以使用'SharedPreference'来存储您的数据。这里是官方的Android文档:[SharedPreference](https://developer.android.com/training/basics/data-storage/shared-preferences.html) – Pulak

+0

你的文件位于哪里? SD卡或内存? –

+0

将文件保存到文件中可能很危险,因为文件可能被移动或删除(或更糟糕)。考虑使用SharedPreferences – Thecave3

您可以将其保存在SharedPrefs 将其更改为

submitBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     String submitAmount = amountEnter.getText().toString(); 
     balance.setText(submitAmount); 
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()). 
edit().putString("balance", submitAmount).commit(); 

    } 
}); 

,您可以通过

String balance=PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) 
.getString("balance","nothing_there"); 
+0

这应该是最正确的答案 – Thecave3

看到您的代码,我假设您知道如何在android中读取/写入文件。如果没有,那么从这里看。 https://*.com/questions/12421814/how-can-i-read-a-text-file-in-android/您可以尝试下面的代码。 readfile方法来自上层链接。您只需从该活动的onCreate方法的文件中读取特定的行/字符串即可。获取所需TextView的引用,然后将文本设置为TextView,如下所示。我希望它能帮助你

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.your_layout); 
     String texts = readfile(); 
     TextView textView = findViewById(R.id.text_view); 
     textView.setText(text); 


} 

private String readfile() { 
    File sdcard = Environment.getExternalStorageDirectory(); 
    File file = new File(sdcard, "file.txt"); 
    StringBuilder text = new StringBuilder(); 

    try { 
     BufferedReader br = new BufferedReader(new FileReader(file)); 
     String line; 

     while ((line = br.readLine()) != null) { 
      text.append(line); 
      text.append('\n'); 
     } 
     br.close(); 
    } catch (IOException e) { 
     //You'll need to add proper error handling here 
    } 

    return text.toString(); 
}