/**
* 写文件
*
* @param in
* 输出的文件流
* @param path
* 文件保存路径
* @throws Exception
*/
public static void writeFile(InputStream in, String path) throws Exception {
byte[] b = new byte[100];
int len;
OutputStream out = new FileOutputStream(new File(path));
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
}
out.close();
}
// /**
// * @param InputStream数据流
// * @return byte[]数据流
// * @throws Exception
// */
// public static byte[] readFile(InputStream is) throws Exception{
// int length = 0;
// length = is.available();
// byte[] bs = new byte[length];
// is.read(bs);
// return bs;
// }
// public byte[] InputStreamToByte(InputStream iStrm) throws IOException {
// ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
// int ch;
// while ((ch = iStrm.read()) != -1){
// bytestream.write(ch);
// }
// byte imgdata[]=bytestream.toByteArray();
// bytestream.close();
// return imgdata;
// }
/**
* @param InputStream数据流
* @return byte[]数据流
* @throws Exception
*/
public static byte[] getBytes(InputStream is)throws Exception{
int length = 0;
length = is.available();
byte[] data = null;
Collection chunks = new ArrayList();
byte[] buffer = new byte[length];
int read = -1;
int size = 0;
while((read=is.read(buffer))!=-1)
{
if(read>0)
{
byte[] chunk = new byte[read];
System.arraycopy(buffer,0,chunk,0,read);
chunks.add(chunk);
size += chunk.length;
}
}
if(size>0)
{
ByteArrayOutputStream bos = null;
try
{
bos = new ByteArrayOutputStream(size);
for(Iterator itr=chunks.iterator();itr.hasNext();)
{
byte[] chunk = (byte[])itr.next();
bos.write(chunk);
}
data = bos.toByteArray();
}
finally
{
if(bos!=null)
{
bos.close();
}
}
}
return data;
}
/**
* @param file
* 文件路径
* @return byte[]数据流
*/
public byte[] readFile(String file) {
File f = new File(file);
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(f));
long contentLength = f.length();
ByteArrayOutputStream outstream = new ByteArrayOutputStream(
contentLength > 0 ? (int) contentLength : 1024);
// byte[] buffer = new byte[4096];
byte[] buffer = new byte[(int) contentLength];
int len;
while ((len = is.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
// byte[] ba = outstream.toByteArray();
outstream.close();
is.close();
// return ba;
return buffer;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}