简体   繁体   中英

BufferedReader.readline() returning null value

I am creating this method which takes an InputStream as parameter, but the readLine() function is returning null . While debugging, inputstream is not empty.

else if (requestedMessage instanceof BytesMessage) {                    
    BytesMessage bytesMessage = (BytesMessage) requestedMessage;
    byte[] sourceBytes = new byte[(int) bytesMessage.getBodyLength()];
    bytesMessage.readBytes(sourceBytes);
    String strFileContent = new String(sourceBytes);                 
    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(sourceBytes);
    InputStream inputStrm = (InputStream) byteInputStream;
    processMessage(inputStrm, requestedMessage);
}


 public void processMessage(InputStream inputStrm, javax.jms.Message requestedMessage) {
    String externalmessage = tradeEntryTrsMessageHandler.convertInputStringToString(inputStrm);
}

public String convertInputStringToString(InputStream inputStream) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }

    br.close();
    return sb.toString();
}

Kindly try this,

BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

i believe that raw data as it is taken is not formatted to follow a character set. so by mentioning UTF-8 (U from Universal Character Set + Transformation Format—8-bit might help

Are you sure you are initializing and passing a valid InputStream to the function?

Also, just FYI maybe you were trying to name your function convertInputStreamToString instead of convertInputStringToString ?

Here are two other ways of converting your InputStream to String, try these maybe?

1.

String theString = IOUtils.toString(inputStream, encoding); 

2.

public String convertInputStringToString(InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is, encoding).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

EDIT: You needn't explicitly convert ByteArrayInputStream to InputStream. You could do directly:

InputStream inputStrm = new ByteArrayInputStream(sourceBytes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM