Android阅读文本文件的速度很慢

时间:2015-11-03 13:03:19

标签: java android

在我的Android应用程序中,我使用FileInputStream来读取文本文件,其大小小于100 kb,并在应用程序中显示其内容。主要问题是虽然文件不是很大,但我的设备打开文件大约需要3-4秒。

考虑到我的设备有1gb ram和一个四核CPU,我想知道我读取文本文件的方式有什么问题,是否有更好的方法使这个过程更快?

String aBuffer = "";
    try {
        File myFile = new File(input);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(
                fIn));
        String aDataRow = "";

        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow + "\n";
        }
        // Toast.makeText(getBaseContext(), aBuffer,
        // Toast.LENGTH_SHORT).show();
        myReader.close();
    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
                .show();
    }

    return aBuffer;

3 个答案:

答案 0 :(得分:7)

你的String concat是一个非常慢的操作。您应该使用StringBuilder执行此任务:

String aDataRow = "";
StringBuilder buffer = new StringBuilder();

while ((aDataRow = myReader.readLine()) != null) {
    buffer.append(aDataRow);
    buffer.append("\n");
}
aDataRow = buffer.toString();

如果你不逐行读取文件,你甚至可以加快读数(因为这可能是一个非常小的缓冲区大小)。您可以设置如下自定义缓冲区大小:

File myFile = new File(input);
FileInputStream fIn = new FileInputStream(myFile);
//needed to shrink the copied array in the last iteration of the length of the content
int byteLength;
//find a good buffer size here.
byte[] buffer = new byte[1024 * 128];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while((byteLength = fIn.read(buffer)) != -1){
    byte[] copy = Arrays.copyOf(buffer, byteLength);
    out.write(copy, 0, copy.length);
}
String output = out.toString();

答案 1 :(得分:3)

  • 找出文件大小。
  • 分配一个大小的缓冲区。
  • 立即将整个文件读入缓冲区(即不要逐行读取,这将会很慢)

答案 2 :(得分:0)

你应该使用线程进行文件读写操作,因为它会降低主线程的速度,从而降低你的读取速度和性能。

相关问题