如何提高写入速度

问题描述 投票:0回答:1

以下代码读取文件中的字节,并使用

Writer
将这些字节作为字符写入另一个文件中。我从此讨论

中提取了它
        String filePath = Display.getInstance().getDatabasePath("TestDB.db");
        FileSystemStorage fss = FileSystemStorage.getInstance();
        InputStream is = fss.openInputStream(filePath);
        byte[] plainBytes = Util.readInputStream(is);

        //encrypt database file content

        Log.p("Starting file encryption...");

        byte[] cipherByteArray = FilesCipher.encryptFile(plainBytes);

        Log.p("Done encrypting file");

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(cipherByteArray);

        String encryptedFilePath = fss.getAppHomePath() + "EncryptedDB.db";

        Log.p("Writing to new a file started..."); 

        try (Writer w = new OutputStreamWriter(fss.openOutputStream(encryptedFilePath), "ISO-8859-1")) {
            int nextChar = byteArrayInputStream.read();
            while (nextChar > -1) {
                char[] charArray = {(char) nextChar};
                w.write(charArray);
                nextChar = byteArrayInputStream.read();
            }

            Log.p("Done writing to a new file");

        } catch (Exception e) {
            Log.p("Error " + e);
        }

如果正在读取的文件的文件大小(例如

TestDB.db
)很小(小于500KB),在模拟器和设备中,
Writer
会非常快地写入新文件(例如
EncryptedDB.db
)。

如果文件很大,例如。

3MB
,在模拟器中写入新文件的速度非常快。但在设备中,它需要的不仅仅是
2 minutes
。我在 Android 10 中测试过。

我已经确认加密速度非常快,因为即使文件很大,即使在设备中,

Log.p("Writing to new a file started...");
也会在
2 Seconds
内执行。

当文件很大时,在模拟器中

Log.p("Done writing to a new file");
会在几秒钟内执行,但在设备中则需要超过
3 minutes
。这意味着
Writer
在设备中速度很慢。

Writer
没有直接写入字节的功能。

如何提高设备中的

Writer
速度?

codenameone
1个回答
0
投票

写/读单个字符总是很慢。您需要使用缓冲区并以两倍的幂读取(如果我没记错的话,我们的默认值是 8192)。

您在设备上分配单个字符数组 300 万次...它在桌面上运行得相当好这一事实令人惊叹。

© www.soinside.com 2019 - 2024. All rights reserved.