-
-
Save byeblogs/b48ca9a22db06a50cafe to your computer and use it in GitHub Desktop.
File To ByteArray in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.baimes.utils; | |
import java.io.*; | |
/** | |
* Created by Ds_Kidd on 2015/4/3 0003. | |
* 将文件转换为byte数组,一般用于图片,视屏,及音频 | |
*/ | |
public class FileToByteArr { | |
/** | |
* 单元测试 | |
*/ | |
public static void main(String[] args){ | |
byte[] b = FileToByteArr.toByteArr("E:\\Users\\Desktop\\1.png"); | |
for(int i = 0;i < b.length;i++){ | |
byte a = b[i]; | |
System.out.println(a); | |
} | |
} | |
/** | |
* 只传入文件绝对路径 | |
* @param path 文件的绝对路径 | |
* @return 当文件存在时,返回byte[],当文件不存在,返回一个长度为0的数组 | |
*/ | |
public static byte[] toByteArr(String path) { | |
try { | |
File file = new File(path); | |
byte[] buffer = null; | |
FileInputStream fileInputStream = new FileInputStream(file); | |
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1000); | |
try { | |
byte[] b = new byte[1000]; | |
int n; | |
while ((n = fileInputStream.read(b)) != -1) { | |
byteArrayOutputStream.write(b, 0, n); | |
} | |
buffer = byteArrayOutputStream.toByteArray(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
}finally { | |
try { | |
fileInputStream.close(); | |
byteArrayOutputStream.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return buffer; | |
}catch (FileNotFoundException e){ | |
e.printStackTrace(); | |
byte[] bytes = new byte[0]; | |
return bytes; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment