文件转换成byte数组
/**
* 文件 File file = new File("...");
* @param filePath
* @return
*/
public static byte[] File2byte(File filePath) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(filePath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
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;
}
byte数组上传到文件
/**
* @param bytes byte数组
* @param fileRoute 文件路径
* @param fileName 文件名
*/
public static void upload(byte[] bytes,String fileRoute,String fileName) {
try {
File directory=new File(fileRoute);
if (!directory.exists()){
directory.mkdirs();
}
File file = new File(directory, fileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}