BufferedReader.readline()返回null值

时间:2015-04-22 09:03:17

标签: java file inputstream

我正在创建此方法,该方法以InputStream为参数,但readLine()函数返回null。在调试时,inputstream不为空。

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();
}

2 个答案:

答案 0 :(得分:0)

请试试这个,

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

我认为原始数据的格式不符合字符集。所以提到UTF-8(U来自通用字符集+转换格式-8位可能有帮助

答案 1 :(得分:0)

您确定要初始化并将有效的InputStream传递给函数吗?

另外,仅仅是因为您可能试图将您的函数命名为 convertInputStreamToString 而不是 convertInputStringToString

以下是另外两种将InputStream转换为String的方法,尝试这些吗?

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() : "";
}

编辑: 您无需将ByteArrayInputStream显式转换为InputStream。你可以直接做:

InputStream inputStrm = new ByteArrayInputStream(sourceBytes);