Reputation: 4929
First off, this is the error I am getting
java.lang.OutOfMemoryError
at coderaustin.com.FileEncryptor.encryptFile(FileEncryptor.java:56)
at coderaustin.com.Main.onCreate(Main.java:41)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
at android.app.ActivityThread.access$2300(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:144)
at android.app.ActivityThread.main(ActivityThread.java:4937)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Obviously I know what the error is, I just don't know how to avoid it. This is what my app does,
You select a file, and click Encrypt. So obviously from there it takes the file, and encrypts it using this code
try {
FileInputStream inFile = new FileInputStream(f.getAbsolutePath());
FileOutputStream outFile = new FileOutputStream(f.getAbsoluteFile() + ".des");
PBEKeySpec keySpec = new PBEKeySpec(text.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey passwordKey = keyFactory.generateSecret(keySpec);
byte[] salt = new byte[8];
Random rnd = new Random();
rnd.nextBytes(salt);
int iterations = 100;
PBEParameterSpec paramaterSpec = new PBEParameterSpec(salt, iterations);
Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
cipher.init(Cipher.ENCRYPT_MODE, passwordKey, paramaterSpec);
outFile.write(salt);
byte[] input = new byte[inFile.available()];
int bytesRead;
while ((bytesRead = inFile.read(input)) != -1)
{
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null) outFile.write(output);
}
byte[] output = cipher.doFinal();
if (output != null) outFile.write(output);
f.delete();
inFile.close();
outFile.flush();
outFile.close();
Yes I know the code is pretty ugly, but it works. Any suggestions?
Thanks all :)
Edit: This is line 56
byte[] input = new byte[inFile.available()];
Upvotes: 2
Views: 1621
Reputation: 64700
Odd: if the file is very big I could see how that could be an issue. Why are you reading the entire file at once instead of reading it in small chunks and processing?
EDIT: try this.
byte[] input = new byte[4096];
int bytesRead;
while ((bytesRead = inFile.read(input, 0, 4096)) != -1)
{
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null) outFile.write(output);
}
Upvotes: 5