android中的文件读取错误。内存不足预期
我正在将返回的字符串转换为字节。在转换为字节时,会出现内存不足异常。有什么想法吗?可能重复:android中的文件读取错误。内存不足预期,android,android-file,Android,Android File,我正在将返回的字符串转换为字节。在转换为字节时,会出现内存不足异常。有什么想法吗?可能重复: 边走边处理文件,而不是立即将整个文件放入内存。据我所知,我假设您在raw文件夹下的resources中存储了一个原始文件,并希望在屏幕上或视图的指定区域显示其内容。如果是这样的话,那么您需要以InputStream类型的变量获取原始文件,如下所示 private String convertStreamToString(InputStream is) throws IOException {
边走边处理文件,而不是立即将整个文件放入内存。据我所知,我假设您在
raw
文件夹下的resources
中存储了一个原始文件,并希望在屏幕上或视图的指定区域显示其内容。如果是这样的话,那么您需要以InputStream
类型的变量获取原始文件,如下所示
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;
}
然后将其传递给将inputStream
转换为字符串的方法,如下所示
InputStream iFile = getResources().openRawResource(R.raw.YOUR_FILE);
方法体inputStreamToString()
应该是这样的:
String strFile = inputStreamToString(iFile);
我正在使用它,它正在工作。下面添加了类的构造函数。public ReadFileManager(Context applicationContext){file=new file(applicationContext.getFilesDir(),Constants.APP_BKP_file)}将整个文件放入内存可能超出了进程允许的数量。你能把文件分解成小块吗?你不是在创建这么大的stringbuilder吗?@Nishant我想你需要StringBuffer
和DataInputStream
在你的convertStreamToString
中。你试过了吗?我觉得文件没那么大。我猜我在某处泄漏内存。@Amr-你能解释更多吗?
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();
}