0

重複の可能性:
ソナー違反:「メソッドは例外でストリームを閉じることができない可能性があります」</a>

私はDataInputStreamを使用するメソッドを持っています、以下のコード:

DataInputStream in = null;
    ServletOutputStream outStream = null;
    FileInputStream fileIn = null;
    URL searchDirectory;
    try {
      searchDirectory = (java.net.URL) ctx.lookup("file/testHarnessDirectory");

      File file = new File(searchDirectory.getPath(), filename);
      int length = 0;
      outStream = response.getOutputStream();
      response.setContentType("application/octet-stream");
      response.setContentLength((int) file.length());

      response.setHeader("Content-Disposition", "attachement; filename=\"" + filename + "\"");
      byte[] byteBuffer = new byte[4096];
      fileIn = new FileInputStream(file);
      in = new DataInputStream(fileIn);

      while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
        outStream.write(byteBuffer, 0, length);
      }
      outStream.close();
      fileIn.close();
      in.close();
    }
    catch (NamingException e) {
      LOG.error("Exception", e);
      throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not download File", e);
    }
    catch (IOException e) {
      LOG.error("Exception", e);
      throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);
    }
    finally {
      try {
        if (fileIn != null) {
          fileIn.close();
        }
        if (in != null) {
          in.close();
        }
        if (outStream != null) {
          outStream.close();
        }
      }
      catch (IOException e) {
        LOG.error("Exception", e);
        throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not submit File", e);}}   

しかし、Sonarは私に次のことを教えてくれます:悪い習慣-メソッドは例外でストリームを閉じることができないかもしれません。私はこの投稿を調べました:ソナー違反:「メソッドは例外でストリームを閉じることができない可能性があります」が、私には不完全に見えました。私は間違っている可能性があります。誰かが私に知らせてもらえますか、ストリームを閉じる簡単な方法は何ですか?

4

1 に答える 1

1

このセクションを確認してください:

 try {
    if (fileIn != null) {
      fileIn.close();
    }
    if (in != null) {
      in.close();
    }
    if (outStream != null) {
      outStream.close();
    }
  }

fileIn.close()失敗したらどうなるか考えてみてください。他の2つのストリームは開いたままになる場合があります。try-catch別のブロックに入れてください。例えば

 try {
    if (fileIn != null) {
      fileIn.close();
    }
  }catch (IOException e) {
    LOG.error("Exception: Could not close file stream", e);
    //throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close file stream", e);
  }
 try {
    if (in != null) {
      in.close();
    }
  }catch (IOException e) {
    LOG.error("Exception: Could not close in stream"", e);
    //throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close in stream", e);
  }
 try {
    if (outStream != null) {
      outStream.close();
    }
  }
  }catch (IOException e) {
    LOG.error("Exception: Could not close out stream", e);
    //throw new CPSException(ErrorCode.FILE_HANDLING_EXCEPTION, "Could not close out stream", e);
  }
于 2012-10-26T00:15:21.103 に答える