public class FileUtils {
public static void main(String[] args) {
File file = new File("F:/opt/temp/MyBatis.pdf");
String name = file.getName();
byte[] buffer = FileToByte(file);
ByteToFile(buffer,"F:/opt/target",name);
}
public static byte[] FileToByte(File file){
byte[] buffer = null;
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1){
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if(fis != null){
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return buffer;
}
public static void ByteToFile(byte[] buf, String filePath, String fileName){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()){
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
} catch (Exception e) {
// TODO: handle exception
} finally {
if(bos != null){
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos != null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
byte[]与File相互转换
最新推荐文章于 2024-06-20 21:14:34 发布