In my java program I would like to read a .txt file in and encode it afterwards. I know how to read a File in and tried to learn how to encode an array. The problem I have is that I don't know how to combine it, it doesn't work the way I tried it.
Here's the part I can read in my text file with:
public class ReadFile { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("test.txt"); BufferedReader br = new BufferedReader(fr); String zeile = ""; do { zeile = br.readLine(); System.out.println(zeile); } while (zeile != null); br.close(); } } In this part I can encrypt and decrypt bytes:
public class Crypt { public static void main(String[] args) { try{ KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); SecretKey myDesKey = keygenerator.generateKey(); Cipher desalgCipher; desalgCipher = Cipher.getInstance("DES"); byte[] text = "test".getBytes("UTF8"); desalgCipher.init(Cipher.ENCRYPT_MODE, myDesKey); byte[] textEncrypted = desalgCipher.doFinal(text); String s = new String(textEncrypted); System.out.println(s); desalgCipher.init(Cipher.DECRYPT_MODE, myDesKey); byte[] textDecrypted = desalgCipher.doFinal(textEncrypted); s = new String(textDecrypted); System.out.println(s); } catch(Exception e) { System.out.println("Error"); } } } I thought to read the text file in and put it in a string to encode it, but I think it is way too complex. Is there another way to connect them, or is another way for encoding required?
FileInputStream,CipherOutputStreammight be the most useful for you)FileInputStreamdirectly on your file, wrap it with aCipherInputStreamthat will encrypt every byte read on the fly and then wrap it again with aReader. That's a more proper way to do things.