读取/写入文件到内部私有存储 [英] Read/write file to internal private storage

查看:24
本文介绍了读取/写入文件到内部私有存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将应用程序从 Symbian/iPhone 移植到 Android,其中一部分是将一些数据保存到文件中.我使用 FileOutputStream 将文件保存到私人文件夹 /data/data/package_name/files:

I'm porting the application from Symbian/iPhone to Android, part of which is saving some data into file. I used the FileOutputStream to save the file into private folder /data/data/package_name/files:

FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE ); 
fos.write( data.getBytes() ); 
fos.close();

现在我正在寻找一种如何加载它们的方法.我正在使用 FileInputStream,但它允许我逐字节读取文件,这非常低效:

Now I am looking for a way how to load them. I am using the FileInputStream, but it allows me to read the file byte by byte, which is pretty inefficient:

int ch;
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = iContext.openFileInput( IDS_LIST_FILE_NAME );
while( (ch = fis.read()) != -1)
  fileContent.append((char)ch);
String data = new String(fileContent);

所以我的问题是如何使用更好的方式读取文件?

So my question is how to read the file using better way?

推荐答案

Using FileInputStream.read(byte[]) 你可以更有效地阅读.

Using FileInputStream.read(byte[]) you can read much more efficiently.

通常,您不希望将任意大小的文件读入内存.

In general you don't want to be reading arbitrary-sized files into memory.

大多数解析器将采用 InputStream.也许您可以让我们知道您如何使用该文件,我们可以提出更合适的建议.

Most parsers will take an InputStream. Perhaps you could let us know how you're using the file and we could suggest a better fit.

以下是您如何使用 read() 的字节缓冲区版本:

Here is how you use the byte buffer version of read():

byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
    fileContent.append(new String(buffer));
}

这篇关于读取/写入文件到内部私有存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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