JavaEar 专注于收集分享传播有价值的技术资料

What to use instead of PrintWriter?

Here is my code that I have which is pretty simple and to the point:

public void sendMessage(String message)
{
    writer.println(message);
    writer.flush();
}

I don't really like to use PrintWriter cause it tends to swallow IOExceptions, this is really the only thing I'm using it for besides sending byte arrays. What can I use instead that won't consume IOExceptions and will still give me the functionality of PrintWriter?

2个回答

    最佳答案
  1. I'd recommend using a plain Writer or a BufferedWriter

    public void writeMessage(BufferedWriter bw, String message) throws IOException {
        bw.write(message);
        bw.newline();
        bw.flush();
    }
    

    or

    public void writeMessage(Writer writer, String message) throws IOException {
        writer.write(message);
        writer.write(System.lineSeparator());
        writer.flush();
    }
    

    But obviously it depends on what functionality of PrintWriter you want to retain.

  2. 参考答案2
  3. If you want to retain PrintWriter and yet check whether any exception has occurred, you can use the checkError() method of PrintWriter to do so. For example, using your own code:

    public void sendMessage(String message)
    {
        try{
            writer.println(message);
        }finally{
               //checkError flushes the stream if it's not closed and checks its error state.
            if(writer.checkError()){ 
                //Your error handling code here
            }
        }
    }
    

    The other way would be to use BufferedReader as @Thilo had suggested in his comment. It would again depend on the functionalities that you would want to retain.

    In case you use an instance of BufferedWriter, you would've the write() methods to work with, which do throw IOException. Read more about them in the javadocs here