将文件读/写到内部私有存储
我正在将应用程序从 Symbian/iPhone 移植到 Android,其中一部分是将一些数据保存到文件中。我使用 FileOutputStream 将文件保存到私有文件夹 /data/data/package_name/files 中:
FileOutputStream fos = iContext.openFileOutput( IDS_LIST_FILE_NAME, Context.MODE_PRIVATE );
fos.write( data.getBytes() );
fos.close();
现在我正在寻找一种加载它们的方法。我正在使用 FileInputStream,但它允许我逐字节读取文件,这是相当低效的:
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);
所以我的问题是如何使用更好的方式读取文件?
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();
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 FileInputStream.read(byte[]) 您可以更有效地阅读。
一般来说,您不希望将任意大小的文件读入内存。
大多数解析器将采用
InputStream
。也许您可以让我们知道您如何使用该文件,我们可以建议更合适的方案。以下是如何使用
read()
的字节缓冲区版本:Using FileInputStream.read(byte[]) you can read much more efficiently.
In general you don't want to be reading arbitrary-sized files into memory.
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()
:这并不是真正特定于 Android 的,而是更面向 Java 的。
如果您更喜欢面向行的读取,则可以将 FileInputStream 包装在 InputStreamReader 中,然后将其传递给 BufferedReader。 BufferedReader 实例有一个 readLine() 方法,您可以使用它来逐行读取。
或者,如果您使用 Google Guava 库,则可以使用 字节流:
This isn't really Android-specific but more Java oriented.
If you prefer line-oriented reading instead, you could wrap the FileInputStream in an InputStreamReader which you can then pass to a BufferedReader. The BufferedReader instance has a readLine() method you can use to read line by line.
Alternatively, if you use the Google Guava library you can use the convenience function in ByteStreams:
//写入
//读取
//to write
//to read
context.getFilesDir() 返回 context.openFileOutput() 进行文件写入的目录的 File 对象。
context.getFilesDir() returns File object of the directory where context.openFileOutput() did the file writing.