【问题标题】:Android: Read text file under /data/data/<package_name>/filesAndroid:读取 /data/data/<package_name>/files 下的文本文件
【发布时间】:2012-03-31 19:40:11
【问题描述】:

我正在尝试读取 /data/data/package_name/files 下的文本文件。

这是我的代码:

private String readTxt(String fileName)
{
    String result = "", line;
    try
    {
        File f = new File(fileName);
        BufferedReader br = new BufferedReader(new FileReader(f));
        while((line = br.readLine()) != null)
        {
            result += line + "\n";
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return result;
}

我做错了什么?

【问题讨论】:

  • 检查fileName的值,你是否有权限读取这个文件。
  • 这不是重点。您始终有权在自己的包目录中读取和写入文件
  • 我发现了问题,我忘了给出路径。它适用于 File f = new File(getFilesDir(), fileName);

标签: android file text


【解决方案1】:

您应该使用应用程序上下文中的 openFileInput 方法。 http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)

这将为您的文件提供 InputStream 例子: 最终的 InputStream 是 = getApplicationContext().openFileInput(MY_FILENAME_WITHOUT_PATH);

【讨论】:

  • 文件是否在缓存文件夹中?
【解决方案2】:
private String getStringFromFile(Context accessClass,String fileName){
    String result=null;
    FileInputStream fIn;
    ContextWrapper accessClassInstance=new ContextWrapper(accessClass);

    try {
        fIn = accessClassInstance.openFileInput(fileName);

        InputSource inputSource=new InputSource(fIn);
                    InputStream in = inputSource.getInputStream();

                  if (in != null) {
                 // prepare the file for reading
                      InputStreamReader input = new InputStreamReader(in);
                      BufferedReader buffreader = new BufferedReader(input);

                 result = "";
                while (( line = buffreader.readLine()) != null) {
                       result += line;
                  }
                     in.close();
      Toast.makeText(getApplicationContext(),"File Contents ==> " + result,Toast.LENGTH_SHORT).show();
      }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 



    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2011-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多