代码如下:
package com.xin.stream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Scanner; import org.apache.commons.io.IOUtils; import com.google.common.io.CharStreams; public class StreamUtil { /** * 将字符串转换为InputStream * @param str * @return */ public InputStream string2InputStream(String str){ return new ByteArrayInputStream(str.getBytes()); } /** * 采用jdk 的scanner 支持jdk1.5以上版本 * @param is * @return */ public String inputStream2String_Scanner(InputStream is){ // InputStream inputStream = new FileInputStream("d:/sample.txt"); StringBuilder stringBuilder = new StringBuilder(); Scanner scanner = new Scanner(is); while(scanner.hasNext()){ String text = scanner.useDelimiter("\\A").next(); stringBuilder.append(text); } scanner.close(); return stringBuilder.toString(); } /** * JDK1.4 及之前的 BufferedReader 法 * @param is * @return */ public String inputStream2String_BufferReader(InputStream is){ StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String line = null; ; try { while((line = bufferedReader.readLine()) != null){ stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } /** * JDK1.4 及之前的 readBytes 法 * 缓冲区的大小自己根据实际来调,比 BufferedReader 还简洁些,不需管换行符的事情。 * @param is * @return * @throws IOException */ public String inputStream2String_bytes(InputStream is) throws IOException{ StringBuilder stringBuilder = new StringBuilder(); byte[] buffer = new byte[1024]; int readBytes = 0; while((readBytes = is.read(buffer)) > 0){ stringBuilder.append(new String(buffer, 0, readBytes)); } return stringBuilder.toString(); } /** * Apache commons IOUtils.toString 法 * 第三方库就是第三方库,人家充分考虑到了你的感受,你对 JDK 库的抱怨,多简洁,一行搞定。 * IOUtils 还能把内容拷入其他的 Writer 中,如 IOUtils.copy(inputStream, new StringWriter())。 * @param is * @return * @throws IOException */ public String inputStream2String_IOUtils(InputStream is) throws IOException{ return IOUtils.toString(is); } /** * Google guava 的 CharStreams 方法 * CharSteams 不是直接作用在 InputSteam 上的,还要靠 InputStreamReader 拱个桥。 * @param is * @return * @throws IOException * @throws UnsupportedEncodingException */ public String inputStream2String_CharStreams(InputStream is) throws UnsupportedEncodingException, IOException{ return CharStreams.toString(new InputStreamReader(is, "UTF-8")); } /** * JDK 7 的 NIO readAllBytes * @param path 读取文件路径 C:\\Users\\Administrator\\Desktop\\ChinaNet上网密码.txt * @return * @throws IOException */ public String inputStream2String_readAllBytes(String path) throws IOException{ byte[] bytes = Files.readAllBytes(Paths.get(path)); String text = new String(bytes); return text; } }
时间: 2024-10-08 04:24:59