What's the best way to suppress a runtime console warning in Java?

前端 未结 7 1511
情歌与酒
情歌与酒 2021-02-07 07:15

I am using the getResponseBody() method of the org.apache.commons.httpclient.methods.PostMethod class. However, I am always getting a message written to the console at runtime:

7条回答
  •  不要未来只要你来
    2021-02-07 07:56

    I would recommend that you do as the warning suggests and use a stream rather than a byte array. If the response you're trying to push is particularly large (suppose it's a large file), you will load it all into memory, and that'd be a very bad thing.

    You're really better off using streams.

    That said, you might hack around it by replacing System.err or System.out temporarily. They're just PrintStream objects, and they're settable with the setOut and setErr methods.

    PrintStream oldErr = System.err;
    PrintStream newErr = new PrintStream(new ByteArrayOutputStream());
    System.setErr(newErr);
    
    // do your work
    
    System.setErr(oldErr);
    

    Edit:

    I agree that it would be preferable to use streams, but as it is now, the target API where I need to put the response is a byte array. If necessary, we can do a refactor to the API that will allow it to take a stream; that would be better. The warning is definitely there for a reason.

    If you can modify the API, do so. Stream processing is the best way to go in this case. If you can't due to internal pressures or whatever, go @John M's route and pump up the BUFFER_WARN_TRIGGER_LIMIT -- but make sure you have a known contentLength, or even that route will fail.

提交回复
热议问题