如何将图片,声音,影像等文件读入字节数组中
来源:互联网 发布:java中贪心算法 编辑:程序博客网 时间:2024/05/17 10:06
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
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();
}
- /**
- * NIO way
- * @param filename
- * @return
- * @throws IOException
- */
- 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){
- // do nothing
- // System.out.println("reading");
- }
- 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();
- }
- }
- }
- /**
- * Mapped File way
- * MappedByteBuffer 可以在处理大文件时,提升性能
- * @param filename
- * @return
- * @throws IOException
- */
- 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) {
- // System.out.println("remain");
- byteBuffer.get(result, 0, byteBuffer.remaining());
- }
- return result;
- }catch (IOException e) {
- e.printStackTrace();
- throw e;
- }finally{
- try{
- fc.close();
- }catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
0 0
- 如何将图片,声音,影像等文件读入字节数组中
- 如何将.txt文件读入到数组
- 将一个文件 读入一个数组中
- 在Oracle中存储图片、影像等大文件
- Python:将文件中的数据读入到数组中
- C++将csv文件数据读入数组中
- C#中如何将打开的TXT文件读入RichTextBox
- 如何把图片、声音等存储到sql中
- 如何把图片、声音等存储到sql中
- 将csv文件读入到数组里
- 将图片读入到Dom中,并将其存为xml文件
- 将图片读入到Dom中,并将其存为xml文件
- 将图片读入到Dom中,并将其存为xml文件
- 关于如何将word文件读入RichTextBox
- 关于如何将word文件读入RichTextBox
- 如何将文件内容读入CString 变量
- 将HDFS文件当中部分字节读入本地
- java中,如何将一个字节数组转换成字符串?
- Spring MVC 学习笔记 json格式的输入和输出
- shell整理
- Oracle学习(十三):闪回
- 抽象工厂模式 (C语言实现)
- struts2零配置(2)
- 如何将图片,声音,影像等文件读入字节数组中
- linxu find 命令 搜索字符串
- Python学习之路——强力推荐的Python学习资料
- 由吃饭想到的产品痛点问题
- [剑指offer]求字符的所有组合
- 目前才知道关于rar的真相
- 二分查找与递归算法
- XCode环境变量及路径设置以及绝对和相对路径
- 第2条:遇到多个构造器参数时要考虑用构建器