Java IO工具类

package com.zhangjun.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author
* @ IO工具类
* */
public class IOUtil {
private IOUtil(){};
/**
* 将流转成字符串
* */
public static String Stream2String(InputStream is)throws IOException{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i=-1;
while((i=is.read())!=-1){
baos.write(i);
}
return new String(baos.toByteArray(),"UTF-8");
};
/**
* 将输入流存储到byte数组中
* @param
*/
public static byte[] in2byte(InputStream is) throws IOException{
byte[] bs= new byte[1024];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = -1;
while((len=is.read(bs))!=-1){
bos.write(bs,0,len);
}
bs = bos.toByteArray() ;
return bs ;
}

/**
* byte数组转换成string
* @param
*/
public static String toString(byte[] input) throws IOException {

return new String(input);

}

/**

* byte数组转换成string
* @param charset 编码格式
*/
public static String toString(byte[] input,String charset) throws IOException {
return new String(input,charset);
}
/**
* 将字符串转换为输入流
* @param charset 编码格式
*/
public static InputStream toInputStream(String input) {
byte[] bytes = input.getBytes();
return new ByteArrayInputStream(bytes);
}
/**

* 将byte数组转换为输入流
* @param charset 编码格式
*/
public static InputStream byte2InputStream(byte[] b){

return new ByteArrayInputStream(b);
};

/**

* 将字符串转换为输入流

* @param input 需要转换的字符串


* @param encoding 编码格式

*/
public static InputStream toInputStream(String input, String encoding) throws IOException {

byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
return new ByteArrayInputStream(bytes);

}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[1024];
while (true) {

int len = in.read(buf);
if (len < 0) break;

out.write(buf, 0, len);


}

}


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值