如何防止发现“Validation.EncodingRequired"在 Java 中 [英] How to prevent the finding "Validation.EncodingRequired" in Java

查看:105
本文介绍了如何防止发现“Validation.EncodingRequired"在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我使用 AppScan Source 扫描编码,它发现了一个我不知道如何修复并传递给扫描仪的发现,或者是误报?

Recently, I used the AppScan Source to scan the coding, and it found out one of the finding which I don't know how to fix and pass to the scanner or is it a false alarm?

这是我的代码.

  public static void copyFileUsingFileStreams(File source, File dest)
    throws IOException
  {
    InputStream input = null;
    OutputStream output = null;
    try
    {
      input = new FileInputStream(source);
      output = new FileOutputStream(dest);
      byte[] buf = new byte[1024];
      int bytesRead;
      while ((bytesRead = input.read(buf)) > 0) {
        output.write(buf, 0, bytesRead); //Scanner reported that's a vulnerability in API OutputStream.write()
      }
    }
    finally
    {
      input.close();
      output.close();
    }
  }

推荐答案

我觉得不错.如果您正在写入字节,则不需要编码.如果你在写角色,那就另当别论了.

Looks fine to me. There's no need for an encoding if you're writing bytes. If you were writing characters, that would be a different matter.

也就是说,您确实应该将流包装在缓冲版本中:

That said, you really ought to be wrapping your streams in buffered versions:

output = new BufferedOutputStream(new FileOutputStream(dest));

input 类似.这不会影响与编码有关的任何事情,但会提高文件 I/O 的效率.

and similarly for input. That doesn't affect anything to do with encodings, but it will make the file I/O more efficient.

您还应该更改 finally 块:

finally
{
    if (input!=null)
        input.close();
    if (output!=null)
        output.close();
}

当您开始捕获并处理 IOException 时,正如您应该做的那样,如果在您的流中出现任何问题,您将面临 NullPointerException正在创建中.

When you start to catch and deal with IOExceptions, as you ought to be doing, you'll be risking a NullPointerException if anything goes wrong while your streams are being created.

这篇关于如何防止发现“Validation.EncodingRequired"在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆