简体   繁体   中英

I wrote the code for encrypting a File. How do I encrypt the contents(files or folders) of the folder?

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

This traverese a file-tree or handles a single file and encrypts every single item

import java.io.File;

public class Encrypter {

    public static void main(String[] args) {
        Encrypter enc = new Encrypter();
        enc.traverseFileTree(new File("root directory or single File"));
    }

    private void traverseFileTree(File node) {
        if (node.isDirectory()) {
            for (String child : node.list()) {
                traverseFileTree(new File(node, child));
            }

            if (node.isFile()) {
                encrypt(node);
            }
        }
    }

    public void encrypt(File file) {

        // your encryption method
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM