Android FileInputStream read() txt 文件到String [英] Android FileInputStream read() txt file to String

查看:36
本文介绍了Android FileInputStream read() txt 文件到String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有专家可以帮助我?在我的 Android 主要活动中,我试图将一个字符串保存到一个文件中,然后在用户之前设置过它的情况下检索它.无法找到任何与我正在做的事情相近的例子.我非常感谢任何帮助!这是我崩溃的测试用例:

Any experts available to help me? In my Android main activity, I'm trying to save a String to a file and then retrieve it if the user has set it before. Wasn't able to find any examples close to what I am doing. I would most appreciate any help! Here is my test case that crashes:

String testString = "WORKS";
String readString;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    FileOutputStream fos;

    try {
        fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
        fos.write(testString.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();

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

    }

    File file = getBaseContext().getFileStreamPath("test.txt");

    if (file.exists()) {

        FileInputStream fis;

        try {
            fis = openFileInput("test.txt");
            fis.read(readString.getBytes());
            fis.close();

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

        } 

        txtDate.setText(String.valueOf(readString));

       } else {
                     // more code
       }
     }
 }

推荐答案

阅读文件试试这个:

FileInputStream fis;
fis = openFileInput("test.txt");
StringBuffer fileContent = new StringBuffer("");

byte[] buffer = new byte[1024];

while ((n = fis.read(buffer)) != -1) 
{ 
  fileContent.append(new String(buffer, 0, n)); 
}

这篇关于Android FileInputStream read() txt 文件到String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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