StreamUtil

[b][color=red]开发者博客:[url]http://www.developsearch.com[/url][/color][/b]

/**
* 流操作
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class StreamUtil {

// 从文件读取数据
public static byte[] getContentFromFile(String filePath) throws IOException
{
FileInputStream fin = new FileInputStream(filePath);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int n = -1;
byte[] buf = new byte[1024];
while ((n = fin.read(buf)) != -1)
{
os.write(buf, 0, n);
}
fin.close();
return os.toByteArray();
}

// 写数据到文件
public static void writeContentToFile(String filePath, byte[] content) throws IOException
{
FileOutputStream fout = new FileOutputStream(filePath, false);

fout.write(content);

fout.close();

}

// 从输入流读取数据
public static byte[] getContentFromInputStream(InputStream in) throws IOException
{
return getContentFromInputStream(in, Integer.MAX_VALUE);
}

// 从输入流读取数据
public static byte[] getContentFromInputStream(InputStream in, int length) throws IOException
{
ByteArrayOutputStream os = new ByteArrayOutputStream();

byte[] buf = new byte[1024];
while (os.size() < length)
{
int n = in.read(buf);
if (n > 0)
{
os.write(buf, 0, n);
}
else if (n < 0)
{
break;
}
}
in.close();
return os.toByteArray();
}

// 从输入流读取数据
public static String getContentStrFromInputStream(InputStream in) throws IOException
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int iCnt = 0;
while ((iCnt = in.read(buf)) > 0)
{
os.write(buf, 0, iCnt);
}
in.close();
return os.toString("UTF-8");
}

public static void main(String[] args)
{
}

/**
* 将输入流的内容全部输出到输出流
*
* @param is 输入流
* @param os 输出流
* @throws IOException
*/
public static void copy(InputStream is, OutputStream os) throws IOException
{
synchronized (is)
{
synchronized (os)
{
byte[] buffer = new byte[256];
while (true)
{
int bytesRead = is.read(buffer);
if (bytesRead == -1)
{
break;
}
os.write(buffer, 0, bytesRead);
}
}
}
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值