java文件转换成byte数组以及byte数组上传到文件
作者:互联网
文件转换成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();
}
}
标签:文件,数组,bos,param,File,directory,new,byte 来源: https://blog.csdn.net/m0_60215634/article/details/122755800