import java.util.Random;
import java.io.*;
class Encrypt
{
public static void main(String args[])
{
try{
String source=System.console().readLine("Enter name of file to be encrypted:- ");
File f1=new File(source);
File f2=new File("~temp");//create a new
FileInputStream fis=new FileInputStream(f1);
FileOutputStream fos=new FileOutputStream(f2);
int a=0;
Random rand=new Random();
int key=0;
while(key==0)
key=rand.nextInt(16);
fos.write(key);
boolean alt=true;
while((a=fis.read())!=(-1))
{
if(alt)
a=a+key;
else
a=a-key;
fos.write(a);
alt=!alt;
}
fos.flush();
fis.close();
fos.close();
f1.delete();
f2.renameTo(f1);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
this code is working fine with any type of file, but it may take more time when the file size is more. Though it will take more time for folder too but i need to do this. I want to pass the folder and encrypt every file in it, and if there is an another folder then the files in that folder should be encrypted. i want to do this for the contents in a folder. What will be the best way to do this?
That is how I run that loop:
File folder = new File("source");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
//my encryption method
} else if (listOfFiles[i].isDirectory()) {
//my encryption method
}
}