内存泄漏使用Java AES对大型音频/视频/ html文件进行加密解密

时间:2017-11-15 06:39:47

标签: java encryption aes

我有一项任务是执行一些大量文件的加密和解密,这些文件由音频,视频和一些html,swf文件组成。为此,我使用的代码在我的系统中运行良好。但是当我尝试使用java RMI在服务器上执行相同的代码时,它会抛出java.lang.OutOfMemoryError Java堆空间。

请建议您的意见如何解决此内存泄漏问题。

以下是我正在使用的代码:

public static void performEncryption(String baseFolderLocation) 
{       
    String key = "This is a secret";

    System.out.println("Started Doing Encrypting...");
    List<File> filenames = getAllfilesInFolder(baseFolderLocation, new ArrayList<File>());
    int processedFilesCount = 0;

    for (File file : filenames) {
        try {

            Crypto.fileProcessor(Cipher.ENCRYPT_MODE, key, file.getAbsoluteFile(), file.getAbsoluteFile());

        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        processedFilesCount++;
    }

    System.out.println("Ended Encrypting...");
}

static void fileProcessor(int cipherMode, String key, File inputFile, File outputFile) {
    try {
        Key secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(cipherMode, secretKey);

        FileInputStream inputStream = new FileInputStream(inputFile);
        byte[] inputBytes = new byte[(int) inputFile.length()];
        inputStream.read(inputBytes);

        byte[] outputBytes = cipher.doFinal(inputBytes);

        FileOutputStream outputStream = new FileOutputStream(outputFile);
        outputStream.write(outputBytes);

        inputStream.close();
        outputStream.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static List<File> getAllfilesInFolder(String directoryName, ArrayList<File> files) {
    File directory = new File(directoryName);

    // get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList) 
    {
        if (file.isFile()) 
        {
            files.add(file);
        }
        else if (file.isDirectory()) 
        {
            getAllfilesInFolder(file.getAbsolutePath(), files);
        }
    }

    return files;
}

1 个答案:

答案 0 :(得分:-1)

您可以尝试使用-Xmx选项增加服务器的Java堆内存吗?