Reputation: 3
I'm trying to write code in Java that will encrypt file. I had used example from this site: http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html
Everything works fine but I need code that will overwrite original file with encrypted one. I'd changed only this:
FileInputStream fis = new FileInputStream("original.txt");
FileOutputStream fos = new FileOutputStream("original.txt");
encrypt(key, fis, fos);
FileInputStream fis2 = new FileInputStream("original.txt");
FileOutputStream fos2 = new FileOutputStream("original.txt");
Encryption works, but after decryption decrypted file is empty. Can someone explain me what's the problem and how to solve it?
Thanks !
Upvotes: 0
Views: 144
Reputation: 269857
You shouldn't read and overwrite the same file simultaneously with FileInputStream
and FileOutputStream
. Often, you'll get lucky, but the behavior is going to vary based on the underlying system, and that's not good. Instead, write to a temporary file, then move the temporary file to the location of the original file.
Upvotes: 2