簡體   English   中英

在Java中進行println之前,如何使代碼等待對象?

[英]How do I make a code wait for an object before proceeding with a println in Java?

我有一個通過采用掃描儀方法並將其加密來加密到Aes-128的代碼。 運行該程序時,加密將終止,而無需等待響應。 我試過了

    try {

         Thread.sleep(10000);

    } catch(InterruptedException ex) {

         Thread.currentThread().interrupt();
    }

但是如果我輸入的時間很長,它將加密

java.util.Scanner [delimiters = \\ p {javaWhitespace} +] [position = 0] [match valid = false] [需要輸入= false] [源關閉= false] [跳過= false] [分組分隔符= \\,] [小數分隔符=。] [正前綴=] [負前綴= \\ Q- \\ E] [正后綴=] [負后綴=] [NaN字符串= \\Q \\ E] [無窮大字符串= \\Q∞\\ E ]

無需等待掃描儀的響應。

這是代碼(這是來自http://aesencryption.net/的修改后的代碼):

    package package1;

    import java.io.UnsupportedEncodingException;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.*;
    import javax.crypto.Cipher;
    import javax.crypto.spec.SecretKeySpec;
    import org.apache.commons.codec.binary.Base64;

    public class AesOne{


    private static SecretKeySpec secretKey;
    private static byte[] key;


    private static String decryptedString;
    private static String encryptedString;

public static void setKey(String myKey){


    MessageDigest sha = null;
    try {
        key = myKey.getBytes("UTF-8");
        System.out.println(key.length);
        sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16);
        System.out.println(key.length);
        System.out.println(new String(key,"UTF-8"));
        secretKey = new SecretKeySpec(key, "AES");


    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

public static String getDecryptedString() {
    return decryptedString;
}
public static void setDecryptedString(String decryptedString) {
    AesOne.decryptedString = decryptedString;
}
public static String getEncryptedString() {
    return encryptedString;
}
public static void setEncryptedString(String encryptedString) {
    AesOne.encryptedString = encryptedString;
}
public static String encrypt(String strToEncrypt)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, secretKey);


        setEncryptedString(Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));

    }
    catch (Exception e)
    {

        System.out.println("Error while encrypting: "+e.toString());
    }
    return null;
}
public static String decrypt(String strToDecrypt)
{
    try
    {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");

        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        setDecryptedString(new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt))));

    }
    catch (Exception e)
    {

        System.out.println("Error while decrypting: "+e.toString());
    }
    return null;
}
public static void main(String args[])
{



            System.out.println("What would you like to encrypt?");

            Scanner encrypt = new Scanner(System.in);
            String toEncrypt = encrypt.toString();

            final String strToEncrypt = toEncrypt;
            final String strPssword = "encryptor key";
            AesOne.setKey(strPssword);

            AesOne.encrypt(strToEncrypt.trim());

            System.out.println("String to Encrypt: " + strToEncrypt); 
            System.out.println("Encrypted: " + AesOne.getEncryptedString());

            final String strToDecrypt =  AesOne.getEncryptedString();
            AesOne.decrypt(strToDecrypt.trim());

            System.out.println("String To Decrypt : " + strToDecrypt);
            System.out.println("Decrypted : " + AesOne.getDecryptedString());

}

}

(我認為縮進可能很奇怪)

你必須用

String toEncrypt = encrypt.next(); 

代替

String toEncrypt = encrypt.toString(); 

然后,掃描儀將一直等到按下Enter鍵。

.toString()立即停止等待的過程,並提供當前Scanner內容的字符串表示形式。

我嘗試了代碼,它工作正常。...如果您是從單元測試開始的(例如,在JUnit中),則單元測試線程可能會在響應返回之前結束。 對於長時間運行的任務,我遇到了這個問題。 如果它在單元測試中 ,則可以嘗試添加這樣的AfterClass調用,以強制單元測試等待...

    @AfterClass
    public static void afterClass() {

        // the threads to finish before we terminate JUNIT
        Thread sleepyThread = new Thread() {
            public void run() {
                // wait for a bit 
                try {
                    this.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        // start the sleepy thread
        try {
            sleepyThread.start();
            sleepyThread.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    System.err.println("Done running tests");

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM