codenameone

How can Writer Speed be Enhanced


The following reads bytes in a file and writes these bytes as characters in another file using Writer. I have extracted it from this discussion

        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);
        }

If file size of the file being read (Eg TestDB.db) is small (less than 500KB), In Simulator & Device, the Writer writes to the new file (Eg. EncryptedDB.db) very fast.

If the file is large eg. 3MB, In Simulator it's written very fast to the new file. But in a device it takes more than 2 minutes. I tested in Android 10.

I have confirmed that encryption is very fast since even when file is large, Log.p("Writing to new a file started..."); is executed within 2 Seconds even in the device.

When file is large, in a Simulator Log.p("Done writing to a new file"); is executed within seconds but in a device it takes more than 3 minutes. This means Writer is slow in a device.

Writer doesn't have a function to write bytes directly.

How can Writer speed be enhanced in devices?


Solution

  • From this Shared Files blog it's also possible to write file bytes directly using OutputStream. That is

    OutputStream outputStream = fss.openOutputStream(encryptedFilePath);
    outputStream.write(cipherByteArray);
    

    A file of size 11.9MB (It has images stored as blob), results to the following log in Android Studio. Encryption completes in 2 sec & writes to the new file in milliseconds

    2024-07-28 11:14:21.109 30329-30415 {App Name}           D  [EDT] 0:0:30,313 - Starting file encryption...
    2024-07-28 11:14:23.733 30329-30415 {App Name}           D  [EDT] 0:0:32,937 - File encryption DONE
    2024-07-28 11:14:23.735 30329-30415 {App Name}           D  [EDT] 0:0:32,940 - Saving encrypted file...
    2024-07-28 11:14:23.767 30329-30415 {App Name}           D  [EDT] 0:0:32,971 - DONE Saving encrypted file