import   java.io.ByteArrayOutputStream; 
import   java.io.File; 
import   java.io.FileInputStream; 
import   java.io.FileNotFoundException; 
import   java.io.FileOutputStream; 
import   java.io.IOException; 
import   java.io.InputStream; 
import   java.io.OutputStream; 
public   class   FileByteUtil   { 
public   static   void   main(String[]   args)   throws   Exception   { 
File   file=new   File( "f:/test.doc "); 
byte[]   fileByte   =   file2byte(file); 
byte2file(fileByte,   "f:/test2.doc "); 
} 
public   static   byte[]   file2byte(File   f)   throws   Exception   { 
  return   file2byte(f.getPath()); 
} 
public   static   byte[]   file2byte(String   f)   throws   Exception   { 
try   { 
InputStream   in   =   new   FileInputStream(f); 
byte[]   tmp   =   new   byte[512]; 
ByteArrayOutputStream   out   =   new   ByteArrayOutputStream(); 
int   bytesRead   =   in.read(tmp); 
while   (bytesRead   !=   -1)   { 
out.write(tmp,   0,   bytesRead); 
bytesRead   =   in.read(tmp); 
} 
return   out.toByteArray(); 
}   catch   (Exception   e)   { 
e.printStackTrace(); 
} 
return   null; 
} 
//   writes   byte   []   to   a   file 
public   static   void   byte2file(byte[]   data,   String   fn)   throws   Exception   { 
try   { 
OutputStream   out   =   new   FileOutputStream(fn); 
out.write(data); 
out.flush(); 
}   catch   (FileNotFoundException   e)   { 
throw   e; 
}   catch   (IOException   e)   { 
throw   e; 
} 
} 
}
	
posted on 2011-06-19 02:01 
三刀流の逆风 阅读(1128) 
评论(0)  编辑  收藏  所属分类: 
JAVA