读/写文件以内部专用存储 [英] Read/write file to internal private storage

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

问题描述

我移植已获得Symbian / iPhone的应用程序到Android,其中一部分是一些数据保存到文件中。我用的的FileOutputStream 以保存文件到私有文件夹 /数据/数据​​/程序包/文件

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 ,但它可以让我读出字节的文件字节,这是pretty的效率低下:

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?

推荐答案

使用<一个href="http://developer.android.com/reference/java/io/FileInputStream.html#read%28byte%5b%5d%29">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.

下面是如何使用字节的缓冲区版本的阅读()

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天全站免登陆