无法修复空指针异常

时间:2014-01-13 03:17:39

标签: java nullpointerexception

我需要一些帮助。

在显示“您的代码已生成”的部分后,继续获取Null Pointer Exception。当我运行我的代码时,我无法弄清楚原因。

在将asHex类添加到同一个包中的新java文件之前,它工作正常,但现在即使删除了asHex也无法工作。

任何人都可以帮助我吗?

代码:

public class myDesCbc2 {

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {


        JFrame frame = null;
        JFileChooser fChoose = new JFileChooser(System.getProperty("user.home"));
        int returnVal = fChoose.showOpenDialog(frame);
        File myFile = fChoose.getSelectedFile();

        FileInputStream fis = new FileInputStream(myFile);
        BufferedReader stream = new BufferedReader(new InputStreamReader(fis, "ISO-8859-1"));
        String file;
        while ((file = stream.readLine()) != null) {

            JOptionPane.showOptionDialog(
                    null, "Generating a 56-bit DES key...", "Processing...", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);

        }
        // Create an 8-byte initialization vector
        SecureRandom sr = new SecureRandom();
        byte[] iv = new byte[8];
        sr.nextBytes(iv);
        IvParameterSpec IV = new IvParameterSpec(iv);

        // Create a 56-bit DES key
        KeyGenerator kg = KeyGenerator.getInstance("DES");

        // Initialize with keysize
        kg.init(56);
        Key mykey = kg.generateKey();

        JOptionPane.showOptionDialog(
                null, "Your key has been generated!", "Processing...", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);

        // Create a cipher object and use the generated key to initialize it
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, mykey, IV);

        byte[] plaintext = file.getBytes("UTF8");

        // Encrypt the text
        byte[] ciphertext = cipher.doFinal(plaintext);

        JOptionPane.showMessageDialog(
                null, "Your ciphertext is" + asHex(ciphertext), "Done!", JOptionPane.PLAIN_MESSAGE);

    }
}

asHex代码:

public class asHex {
      public static String asHex (byte buf[]) {
         StringBuffer strbuf = new StringBuffer(buf.length * 2);
         int i;

           for (i = 0; i < buf.length; i++) {
              if (((int) buf[i] & 0xff) < 0x10)
                strbuf.append("0");

                strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
              }

           return strbuf.toString();
  }

}

1 个答案:

答案 0 :(得分:1)

将while循环后的代码放在while循环中,这应解决问题。否则,当执行while循环后的代码导致错误时,该文件为空。

相关问题