0

(致版主)请注意我之前发布过一个相关问题,但这是一个更完整的帖子,所以请不要将其关闭为重复。你可以关闭之前的帖子。

每当我在控制台输出中得到 -1 时,输出流中都不会写入任何数据,每当我在控制台输出中得到 3 时,输出流中都会写入有效数据。-1 和 3 的出现在不同的场合是随机的。

这是代码

public void decrypt(InputStream in, OutputStream out) {
  try {
    // Bytes read from in will be decrypted
    in = new CipherInputStream(in, dcipher);

    // Read in the decrypted bytes and write the cleartext to out
    int numRead = 0;
    System.out.println(in.read(buf));
    while ((numRead = in.read(buf)) >= 0) {
      out.write(buf, 0, numRead);
    }
    //out.close();
  }
  catch (java.io.IOException e) {
  }
}

这是控制台输出

the Cell Content : ¼OKs>N?h¸GX&ŸH
-1
the Cell Content : 3Ëù%¥þ-]'±ŠM݆
3
the Cell Content : ´`?û…óï>»†µýÆ$
-1
the Cell Content : 9ûÊ‘øxIÐ8`ýÊeú
3
the Cell Content : •x€ÌWã’ç4æ~?Gû{
-1
the Cell Content : ÉJ‹SD
-1
the Cell Content : ¯'´öƒ²wCÐ)/
3
the Cell Content : ¼?\š
-1
the Cell Content : 4¤¢ÃUÚړ‹ïEk?É•
-1
the Cell Content : vì=¨;°e¼~{GÀ“È"?
3
the Cell Content : 0ò*"MoañôefU?ô?
-1
the Cell Content : –çä,M9"kIF FJÅ
3
the Cell Content : ¬¼aâÅ•b鉭-SoP~Æ
3
the Cell Content : œ¦LKØ•0I¾>n=á
3
the Cell Content : Å'?X °¡¯“nJ/0è˜
3
the Cell Content : 3™æ&‡õvâr`õ_4¾õ
3
the Cell Content : l羚jT/`‚«h™&
3
the Cell Content : ~à‘_X;eÜ$8º!šŒì
3
the Cell Content : ùݳ9ˆ>‰Liœr‡
3
the Cell Content : UzÛ,­»è–­Üí‡AB®µ
3
the Cell Content : ’ùZnë¥æFó¦–ñ?~
-1
the Cell Content : 4ê¶È˜¬ ”Ôÿ4vä
3

这是对解密函数的调用。

InputStream excelResource=new FileInputStream(path);
Workbook rwb=Workbook.getWorkbook(excelResource);
int sheetCount=rwb.getNumberOfSheets();
Sheet rs = rwb.getSheet(0);
int rows = rs.getRows();
int cols = rs.getColumns();
for(int i=0; i<rows; i++) {
  for(int j=0; j<Col.length; j++) {
    String theCell_00 = rs.getCell(j,i).getContents();
    System.out.println("the Cell Content : " + theCell_00);

    in = new ByteArrayInputStream(theCell_00.getBytes());
    out = new FileOutputStream("c:\\Decrypted.txt");
    encrypter.decrypt(in, out);

创建输入流的 excel 文件在每个单元格上都有数据,这些数据显示在控制台输出的单元格内容中。请帮助我找出为什么即使使用有效的输入流(看起来像)我得到 -1 控制台输出。

4

3 回答 3

10

删除这个无意义的行:

System.out.println(in.read(buf));

确实将数据读入缓冲区,但您进一步忽略了它!您在while语句中执行的下一次调用不会读回相同的数据,而只会读取超出缓冲区长度的下一个字节。numRead如果您真的感兴趣,最好在循环内部进行 sysout 。

另一个问题是您正在用另一个in替换参数: InputStream

in = new CipherInputStream(in, dcipher);

将其分配给自己的局部变量并保持方法参数不变。最好final在将来声明它们,以便编译器会给出错误。例如

public void decrypt(final InputStream in, final OutputStream out)

或者,您也可以将 IDE 配置为在覆盖方法参数时显示警告(这通常是一种不好的做法)。在例如 Eclipse 中,您可以通过Java > Compiler > Errors/Warnings > Name shadowing and conflict > 全部设置为WarningError来执行此操作。

于 2009-11-25T13:47:43.810 回答
1

只是一个想法,尽量不要in用于加密/清除输入流。如中,

  public void decrypt(InputStream ciph_in, OutputStream out) {
  InputStream in;
  try {
    // Bytes read from in will be decrypted
    in = new CipherInputStream(ciph_in, dcipher);

看看会发生什么。

于 2009-11-25T14:10:47.040 回答
1

除了在此处和在其他问题中检测到的其他问题外,我认为您的真正问题可能与encoding有关。Excel文件的编码是什么?

知道编码是什么后,您可以执行以下操作:

theCell_00.getBytes("MYENCODING");

另外,你能告诉我们你是如何创建密码的,如果可能的话,密钥?

于 2009-11-25T14:29:52.137 回答