java中如何把一个文件转化为byte数组

File file = new File("E:/girl.png");
我该如何把这个得到这个file的byte数组

java将文件转换为byte数组,主要是使用输出流,实例如下:

/** 
     * æ ¹æ®byte数组,生成文件 
     */  
    public static void getFile(byte[] bfile, String filePath,String fileName) {  
        BufferedOutputStream bos = null;  //新建一个输出流
        FileOutputStream fos = null;  //w文件包装输出流
        File file = null;  
        try {  
            File dir = new File(filePath);  
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在  
                dir.mkdirs();  
            }  
            file = new File(filePath+"\\"+fileName);  //新建一个fileç±»
            fos = new FileOutputStream(file);  
            bos = new BufferedOutputStream(fos);  //输出的byte文件
            bos.write(bfile);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  //关闭资源
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  //关闭资源
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
    }
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2018-07-09
import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

public class Test {

public static void main(String[] args) {

// TODO Auto-generated method stub

try{

getBytesFromFile(new File("C:\\aaa.txt"));

}catch(IOException e){

System.out.println("IOException");

}

}

// 返回一个byte数组

public static byte[] getBytesFromFile(File file) throws IOException {

InputStream is = new FileInputStream(file);

// 获取文件大小

long length = file.length();

if (length > Integer.MAX_VALUE) {

// 文件太大,无法读取

throw new IOException("File is to large "+file.getName());

}

// 创建一个数据来保存文件数据

byte[] bytes = new byte[(int)length];

// 读取数据到byte数组中

int offset = 0;

int numRead = 0;

while (offset < bytes.length

&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {

offset += numRead;

}

// 确保所有数据均被读取

if (offset < bytes.length) {

throw new IOException("Could not completely read file "+file.getName());

}

// Close the input stream and return bytes

is.close();

return bytes;

}

}本回答被提问者和网友采纳
第2个回答  2019-05-23
/**
* 获得指定文件的byte数组
*/
public byte[] getBytes(String filePath){
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}

fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
第3个回答  2018-03-22
答非所问 真服气这种人
相似回答