我的代碼解密文件夾中的所有加密文件,但我使用了Thread.sleep()。如果我不使用Thread.sleep();程序無法解密所有文件。我正在尋找更好的方式來解密沒有Thread.sleep()的所有文件。Decrypting files via Runtime.getRuntime()。exec without Thread.sleep()
我需要在代碼中寫入條件,其中此代碼正在等待文件被解密。你可以幫幫我嗎?
我的代碼:
public static void decrypt() throws InterruptedException, IOException {
File folder = new File("c:/Users/hajdukri/Desktop/src");
File[] files = folder.listFiles();
String pass;
Scanner in = new Scanner(System.in);
System.out.println("Enter a password");
pass = in.nextLine();
if("pass123456".equals(pass)){
for(File a :files){
Thread.sleep(500);
Runtime.getRuntime().exec("cmd /C start C:\\Users\\hajdukri\\Documents\\NetBeansProjects\\JavaApplication3\\gpg.bat");
if (a.isFile()) {
String fileName = a.getName();
// get only only last index (exeption)
int co = fileName.lastIndexOf('.')+1;
StringBuilder sb = new StringBuilder(fileName);
sb.delete(0, co);
sb.toString();
if ("gpg".equals(sb.toString())){
int last = fileName.lastIndexOf('.');
StringBuilder delLast = new StringBuilder(fileName);
delLast.delete(last, 4+last);
delLast.toString();
File file = new File("C:\\Users\\hajdukri\\Documents\\NetBeansProjects\\JavaApplication3\\gpg.bat");
String content = "cd C:\\Users\\hajdukri\\Desktop\\src \r\ngpg --output "+ delLast +" --batch --passphrase "+"\""+pass+"\""+ " "+" --decrypt "+ fileName +"\r\nexit b/";
FileWriter fw = new FileWriter(file.getAbsoluteFile());
try (BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(content);
bw.close();
}
}
}
}
}
else{
System.out.println("Invalid password entered!");}
}
我只需要在以前的文件decripted下一個文件運行調用Runtime.getRuntime()EXEC(gpg.bat)。
非常感謝。
Runtime.getRuntime()。exec()返回一個Process對象。使用對象waitFor()方法等待,直到你的子進程完成。 –
我使用了waitFor(),但代碼無法正常工作。我試圖解密文件夾中的5個文件,但該程序只解密4個,有時只有3個文件。 – Xhyzors
將調試狀態代碼添加到您的代碼中,以確切查看它卡住的位置。如果你有時說它解密到4個文件,最後一個失敗可能會出現問題。 –