cyr*_*oxx 7 java string inputstream character-encoding
我需要将InputStream的内容转换为String.这里的难点是输入编码,即Latin-1.我尝试了几种方法和代码片段,包括String,getBytes,char []等,以便直接获得编码,但似乎没有任何效果.
最后,我想出了下面的工作解决方案.但是,这个代码对我来说似乎有点冗长,即使对于Java也是如此.所以这里的问题是:
有没有更简单,更优雅的方法来实现这里所做的事情?
private String convertStreamToStringLatin1(java.io.InputStream is)
throws IOException {
String text = "";
// setup readers with Latin-1 (ISO 8859-1) encoding
BufferedReader i = new BufferedReader(new InputStreamReader(is, "8859_1"));
int numBytes;
CharBuffer buf = CharBuffer.allocate(512);
while ((numBytes = i.read(buf)) != -1) {
text += String.copyValueOf(buf.array(), 0, numBytes);
buf.clear();
}
return text;
}
Run Code Online (Sandbox Code Playgroud)
首先,对你已采取的方法提出一些批评.CharBuffer当你只想要一个NIO 时,你不应该不必要地使用NIO char[512].clear每次迭代都不需要缓冲区.
int numBytes;
final char[] buf = new char[512];
while ((numBytes = i.read(buf)) != -1) {
text += String.copyValueOf(buf, 0, numBytes);
}
Run Code Online (Sandbox Code Playgroud)
您还应该知道,只使用这些参数构造aString将具有相同的效果,因为构造函数也会复制数据.
子阵列的内容被复制; 后续修改字符数组不会影响新创建的字符串.
您可以使用动态ByteArrayOutputStream增加内部缓冲区来容纳所有数据.然后,您可以使用整个byte[]from toByteArray来解码为String.
优点是推迟解码直到最后避免单独解码片段; 虽然这可能适用于简单的字符集,如ASCII或ISO-8859-1,但它不适用于UTF-8和UTF-16等多字节方案.这意味着将来更容易更改字符编码,因为代码不需要修改.
private static final String DEFAULT_ENCODING = "ISO-8859-1";
public static final String convert(final InputStream in) throws IOException {
return convert(in, DEFAULT_ENCODING);
}
public static final String convert(final InputStream in, final String encoding) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final byte[] buf = new byte[2048];
int rd;
while ((rd = in.read(buf, 0, 2048) >= 0) {
out.write(buf, 0, rd);
}
return new String(out.toByteArray(), 0, encoding);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13155 次 |
| 最近记录: |