BlackBerry InputStream to String conversion

佐手、 提交于 2019-12-21 02:47:28

问题


How do I convert an InputStream to a String on a BlackBerry?


回答1:


I would store the data from the inputStream in a StringBuffer. The code would look like this:

byte[] buffer = new byte[1024];
StringBuffer sb = new StringBuffer();
int readIn = 0;
while((readIn = inputStream.read(buffer)) > 0)
{
     String temp = new String(buffer, 0, readIn);
     sb.append(temp);  
}
String result = sb.toString();



回答2:


How about this for minimal code:

String str = new String(IOUtilities.streamToBytes(is), "UTF-8");



回答3:


Jonathan's approach assumes your bytes represent a String in default BlackBerry encoding (ISO-8859-1). However most modern apps are multy-languaged, so the best encoding to support is UTF-8. To respect a set encoding you may use smth like this:

/**
 * Constructs a String using the data read from the passed InputStream.
 * Data is read using a 1024-chars buffer. Each char is created using the passed 
 * encoding from one or more bytes.
 * 
 * <p>If passed encoding is null, then the default BlackBerry encoding (ISO-8859-1) is used.</p>
 * 
 * BlackBerry platform supports the following character encodings:
 * <ul>
 * <li>"ISO-8859-1"</li>
 * <li>"UTF-8"</li>
 * <li>"UTF-16BE"</li>
 * <li>"UTF-16LE"</li>
 * <li>"US-ASCII"</li>
 * </ul>
 * 
 * @param in - InputStream to read data from.
 * @param encoding - String representing the desired character encoding, can be null.
 * @return String created using the char data read from the passed InputStream.
 * @throws IOException if an I/O error occurs.
 * @throws UnsupportedEncodingException if encoding is not supported.
 */
public static String getStringFromStream(InputStream in, String encoding) throws IOException {
    InputStreamReader reader;
    if (encoding == null) {
        reader = new InputStreamReader(in);
    } else {
        reader = new InputStreamReader(in, encoding);            
    }

    StringBuffer sb = new StringBuffer();

    final char[] buf = new char[1024];
    int len;
    while ((len = reader.read(buf)) > 0) {
        sb.append(buf, 0, len);
    }

    return sb.toString();
}


来源:https://stackoverflow.com/questions/4313845/blackberry-inputstream-to-string-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!