Search code examples
javastringsocketsheap-memoryinputstream

Converting InputStreamReader into String


Is there a better way to read Strings from an InputStreamReader. In the Profiler im am getting a memory heap there.

public String getClientMessage() throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(tempSocket.getInputStream()));     
    char[] buffer = new char[200];
    return new String(buffer, 0, bufferedReader.read(buffer));
}

Thanks in advance.

EDIT: enter image description here

EDIT: Messages are sent with this:

public void sendServerMessage(String action) throws IOException{
    PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(tempSocket.getOutputStream()));
    printWriter.print(action);
    printWriter.flush();
}

Solution

  • You can use IOUtils, but it is easy to write if you can't use that library.

    public String getClientMessage() throws IOException {
        Reader r = new InputStreamReader(tempSocket.getInputStream());
        char[] buffer = new char[4096];
        StringBuilder sb = new StringBuilder();
        for(int len; (len = r.read(buffer)) > 0;)
             sb.append(buffer, 0, len);
        return sb.toString();
    }
    

    I suspect the problem is you have no way of know from the way you send messages when a message stops. This means you must read until you close the connection which you are not doing. If you don't want to wait until you close you need to add some way of knowing when a message is finished e.g. a newline.

    // create this once per socket.
    final PrintWriter out = new PrintWriter(
          new OutputStreamWriter(tempSocket.getOutputStream(), "UTF-8"), true);
    
    public void sendServerMessage(String action) {
        // assuming there is no newlines in the message
        printWriter.println(action);  // auto flushed.
    }
    
    // create this once per socket
    BufferedReader in = new BufferedReader(
        new InputStreamReader(tempSocket.getInputStream(), "UTF-8"));     
    
    public String getClientMessage() throws IOException {
         // read until the end of a line, which is the end of a message.
          return in.readLine();
    }