关于InputStream 和String对象之间的相互转换

代码如下:

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-07-29 18:09:30

关于InputStream 和String对象之间的相互转换的相关文章

byte数组与对象之间的相互转换

在进行网络通信时可能需要传输对象,如果用NIO的话,只能用Bytebuffer和channel直接 通过ByteArray*Stream和Object*Stream可以将byte数组和对象进行相互的转换. 1.byte数组转对象: byte [] data=initData();//初始化byte数组 ByteArrayInputStream inputStream=new ByteArrayInputStream(data); ObjectInputStream oInputStream=ne

char * string nsstring 之间的相互转换

std::string转NSString std::string _string("hello"); NSString *str= [NSString stringWithCString:_string.c_str() encoding:[NSString defaultCStringEncoding]]; NSString转std::string NSString * nsfaceName[email protected]"HELLO"; const char *

速战速决 (6) - PHP: 获取 http 请求数据, 获取 get 数据 和 post 数据, json 字符串与对象之间的相互转换

[源码下载] 作者:webabcd 介绍速战速决 之 PHP 获取 http 请求数据 获取 get 数据 和 post 数据 json 字符串与对象之间的相互转换 示例1.获取 http 请求数据http/http1.php <?php /** * 获取 http 请求数据 */ // 通过 $_SERVER 获取相关数据 echo "PHP_SELF : " . $_SERVER['PHP_SELF'] . "<br />"; echo &qu

CString, string, char *之间的相互转换(转)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Date: 2018.09.02 1. string→CString CString.format("%s", string.c_str()); 2. CString→string string str(CString.GetBuffer(str.GetLength(

C# Enum Name String Description之间的相互转换

最近工作中经常用到Enum中Value.String.Description之间的相互转换,特此总结一下. 1.首先定义Enum对象 1 public enum Weekday 2 { 3 [Description("星期一")] 4 Monday=1, 5 [Description("星期二")] 6 Tuesday=2, 7 [Description("星期三")] 8 Wednesday=3, 9 [Description("星期

java int和String类型之间的相互转换

String --> int 第一种方法:int i = Integer.parseInt(s); 第二种方法:int i = Integer.valueOf(s).intValue(); 两种方法的区别:Integer.valueOf(s) 相当于 new Integer(Integer.parseInt(s)),所以第二种方法会产生多余的一个对象,而第一种方法不会. int --> String 第一种方法:String s = i + ""; 第二种方法:String

[技巧篇]19.InputStream与String,Byte之间互转[转载]

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * @see InputStream转化为String String 转换为InputStream InputStream 转化为byte数组 byte转化为InputStream byte转化为String * @author

InputStream与String,Byte之间互转

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * * @author Andy.Chen * @mail [email protected] * */ public class InputStreamUtils { final static int BUFFER_SIZE =

c++中char*\wchar_t*\string\wstring之间的相互转换

最近在编程中经常遇到需要多字节字符与宽字节字符相互转换的问题,一直自己贴那几句代码.觉得麻烦,于是就自己写了一个类来封装wchar_t与char类型间的转换, 其他的,诸如:CString\ LPWSTR\TCHAR   CHAR\LPSTR之间也是一样用 头文件: #ifndef USE_H_ #define USE_H_ #include <iostream> #include <windows.h> #include <string> using namespac