/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public
static
byte
[] readFileByBytes(String fileName) {
InputStream in =
null
;
ByteArrayOutputStream out =
new
ByteArrayOutputStream();
try
{
in =
new
FileInputStream(fileName);
byte
[] buf =
new
byte
[
1024
];
int
length =
0
;
while
((length = in.read(buf)) != -
1
) {
out.write(buf,
0
, length);
}
}
catch
(Exception e1) {
e1.printStackTrace();
}
finally
{
if
(in !=
null
) {
try
{
in.close();
}
catch
(IOException e1) {
}
}
}
return
out.toByteArray();
}
-
-
-
-
-
-
- public static byte[] toByteArray2(String filename)throws IOException{
-
- File f = new File(filename);
- if(!f.exists()){
- throw new FileNotFoundException(filename);
- }
-
- FileChannel channel = null;
- FileInputStream fs = null;
- try{
- fs = new FileInputStream(f);
- channel = fs.getChannel();
- ByteBuffer byteBuffer = ByteBuffer.allocate((int)channel.size());
- while((channel.read(byteBuffer)) > 0){
-
-
- }
- return byteBuffer.array();
- }catch (IOException e) {
- e.printStackTrace();
- throw e;
- }finally{
- try{
- channel.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- try{
- fs.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
-
-
-
-
-
-
-
-
- public static byte[] toByteArray3(String filename)throws IOException{
-
- FileChannel fc = null;
- try{
- fc = new RandomAccessFile(filename,"r").getChannel();
- MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
- System.out.println(byteBuffer.isLoaded());
- byte[] result = new byte[(int)fc.size()];
- if (byteBuffer.remaining() > 0) {
-
- byteBuffer.get(result, 0, byteBuffer.remaining());
- }
- return result;
- }catch (IOException e) {
- e.printStackTrace();
- throw e;
- }finally{
- try{
- fc.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }