android中的文件读取错误。内存不足异常

时间:2014-06-02 06:25:39

标签: android android-file

private String convertStreamToString(InputStream is) throws IOException 
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line).append("\n");
        }
        reader.close();
        return sb.toString();
    }

protected String getStringFromFile(Context applicationContext) throws IOException 
{
    FileInputStream fin = new FileInputStream(file);
    String ret = convertStreamToString(fin);
    // Make sure you close all streams.
    fin.close();
    return ret;
}

我将返回的字符串转换为字节。转换为字节时,它会给出内存不足异常。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

据我了解您的问题,我假设您有一个原始文件存储在resources raw下的InputStream文件夹中,并希望在屏幕上或视图的指定区域显示其内容。如果是这样,那么你需要将原始文件放在InputStream iFile = getResources().openRawResource(R.raw.YOUR_FILE); 类型的变量中,如下所示

inputStream

然后将其传递给将string转换为String strFile = inputStreamToString(iFile); 的方法,就像这样

inputStreamToString()

方法private String inputStreamToString(InputStream iFile) throws IOException { // TODO Auto-generated method stub StringBuffer sBuffer = new StringBuffer(); DataInputStream dataIO = new DataInputStream(iFile); String strLine = null; while ((strLine = dataIO.readLine()) != null) { sBuffer.append(strLine + "\n"); } dataIO.close(); iFile.close(); return sBuffer.toString(); } 的主体应该是这样的:

{{1}}

我正在使用它并且它正在工作。

答案 1 :(得分:0)

可能重复:java outOfMemoryError with stringbuilder

随时处理文件,而不是立即将整个文件存入内存。