其实我只是偶尔上Stack Overflow,直到看了这个200万次阅读量的提问:HowdoI read/convert anInputStreamintoaStringinJava?
惊呆了!!!
怎么会有这么多人围观。
我第一反应的解决办法是使用 Apachecommons包的工具类 IOUtils,果不其然,第一条回答就是这个。
我的天!居然有2000+的赞!
继续往下看,发现大家的不少的骚操作
使用CharStreams (Guava)
1 | String result = CharStreams.toString(new InputStreamReader( |
使用Scanner
1 | Scanner s = new Scanner(inputStream).useDelimiter("\\A"); |
使用Stream API
Warning: This solution converts different line breaks (like \r\n) to \n.
1 | String result = new BufferedReader(new InputStreamReader(inputStream)) .lines().collect(Collectors.joining("\n")); |
使用parallel Stream API
Warning: This solution converts different line breaks (like \r\n) to \n.
1 | String result = new BufferedReader(new InputStreamReader(inputStream)).lines() .parallel().collect(Collectors.joining("\n")); |
使用InputStreamReader and StringBuilder
1 | final int bufferSize = 1024; |
使用StringWriter and IOUtils.copy
1 | writer = new StringWriter(); |
使用ByteArrayOutputStream and inputStream.read
1 | ByteArrayOutputStream result = new ByteArrayOutputStream(); |
使用BufferedReader
Warning: This solution converts different line breaks (like \n\r) to line.separator system property (for example, in Windows to “\r\n”).
1 | String newLine = System.getProperty("line.separator"); |
使用 BufferedInputStream and ByteArrayOutputStream
1 | BufferedInputStream bis = new BufferedInputStream(inputStream); |
使用 inputStream.read() and StringBuilder
Warning: This solution has problems with Unicode, for example with Russian text (works correctly only with non-Unicode text)
1 | int ch; |
甚至,还贴出了微基准测试的结果,果然狠人啊。
对于小字符串(length = 175) 结果如下:mode = Average Time, system = Linux, score 1,343 is the best :
1 | Benchmark Mode Cnt Score Error Units |
对于大字符串(length = 50100) 结果如下:mode = Average Time, system = Linux, score 200,715 is the best
1 | Benchmark Mode Cnt Score Error Units |
如获宝藏,看来需要时不时的逛逛Stack Overflow了。
参考
原文出处:
微信公众号:Java比比