java - 为什么我一直得到-1作为in.read(buf)的值?

rov*_*r12 0 java encryption aes

(对主持人)请注意我之前发布了一个相关问题,但这是一个更完整的帖子所以请不要将其作为重复关闭.你可以关闭上一篇文章.

每当我在控制台输出中得到-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) {
  }
}
Run Code Online (Sandbox Code Playgroud)

这是控制台输出

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
Run Code Online (Sandbox Code Playgroud)

这是对解密函数的调用.

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);
Run Code Online (Sandbox Code Playgroud)

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

Bal*_*usC 10

删除这个无意义的行:

System.out.println(in.read(buf));
Run Code Online (Sandbox Code Playgroud)

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

另一个问题是你in要用另一个 替换参数InputStream:

in = new CipherInputStream(in, dcipher);
Run Code Online (Sandbox Code Playgroud)

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

public void decrypt(final InputStream in, final OutputStream out)
Run Code Online (Sandbox Code Playgroud)

或者,您也可以配置IDE以在覆盖方法参数时显示警告(这通常是一种不好的做法).例如,Eclipse可以通过Java > Compiler > Errors/Warnings > Name shadowing and conflicts > all all to Warning或者Error来完成.

  • @ rover12:对不起我?我想你应该提供更好的SSCCE.请你的态度,现在看起来你正在把自己的错误转移到我身边.这并不能真正鼓励我进一步帮助你. (4认同)