使用CharStreams(Guava)String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
使用Scanner(JDK)String result = CharStreams.toString(new InputStreamReader( inputStream, Charsets.UTF_8));
使用Stream API(Java 8)。警告:此解决方案会将不同的换行符(如rn)转换为n。Scanner s = new Scanner(inputStream).useDelimiter("\A");String result = s.hasNext() ? s.next() : "";
使用并行流API(Java 8)。警告:此解决方案会将不同的换行符(如rn)转换为n。String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("n"));
使用InputStreamReader和StringBuilder(JDK)String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("n"));
使用StringWriter和IOUtils.copy(Apache Commons)final int bufferSize = 1024;final char[] buffer = new char[bufferSize];final StringBuilder out = new StringBuilder();Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);int charsRead;while((charsRead = in.read(buffer, 0, buffer.length)) > 0) { out.append(buffer, 0, charsRead);}return out.toString();
使用ByteArrayOutputStream和inputStream.read(JDK)StringWriter writer = new StringWriter();IOUtils.copy(inputStream, writer, "UTF-8");return writer.toString();
使用BufferedReader(JDK)。警告:此解决方案将不同的换行符(如nr)转换为line.separator系统属性(例如,在Windows中转换为“ r n”)。ByteArrayOutputStream result = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length;while ((length = inputStream.read(buffer)) != -1) { result.write(buffer, 0, length);}// StandardCharsets.UTF_8.name() > JDK 7return result.toString("UTF-8");
使用BufferedInputStream和ByteArrayOutputStream(JDK)String newline = System.getProperty("line.separator");BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder result = new StringBuilder();boolean flag = false;for (String line; (line = reader.readLine()) != null; ) { result.append(flag? newline: "").append(line); flag = true;}return result.toString();
使用inputStream.read()和StringBuilder(JDK)。警告:此解决方案存在Unipre问题,例如俄语文本(仅适用于非Unipre文本)BufferedInputStream bis = new BufferedInputStream(inputStream);ByteArrayOutputStream buf = new ByteArrayOutputStream();int result = bis.read();while(result != -1) { buf.write((byte) result); result = bis.read();}// StandardCharsets.UTF_8.name() > JDK 7return buf.toString("UTF-8");
int ch;StringBuilder sb = new StringBuilder();while((ch = inputStream.read()) != -1) sb.append((char)ch);reset();return sb.toString();
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)