[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);
}
}
}
}
}