Java 文件和byte数组转换
2016-10-28 10:00
387 查看
public class T3 { public static void main(String[] args){ String filePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src\\1.docx"; String outFilePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src"; String outFileName = "2.docx"; getFile(getBytes(filePath),outFilePath,outFileName); } /** * 获得指定文件的byte数组 */ public static byte[] getBytes(String filePath){ byte[] buffer = null; try { File file = new File(filePath); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; 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数组,生成文件 */ public static void getFile(byte[] bfile, 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+"\\"+fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); 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(); } } } } }
相关文章推荐
- java 实现 图片文件 与 byte 数组互相转换
- JAVA中文件与Byte数组相互转换的方法
- java 文件和byte数组相互转换
- Java byte数组和文件相互转换
- java 文件操作之byte数组间的转换
- Java 文件和byte数组转换
- JAVA 把File文件转换成Byte[]数组的标准写法
- 【转载】java输入流转为文件 InputStreamToFile 以及 byte[]和InputStream的相互转换
- java中byte数组与int类型的转换(两种方式)
- java中byte数组与int类型之间的相互转换(两种方式)
- java文件与byte[]的转换
- [转]java中long,int,short与byte数组之间的转换
- Java byte数组到long的转换
- JAVA里面关于byte数组和String之间的转换问题
- java byte数组与文件读写
- java整型数与网络字节序的 byte[] 数组转换关系
- java中short,int转换成byte数组及byte数组转换成short,int
- JAVA中实现图片对象转换成图片文件和字节数组(Byte[ ])的方法讨论
- Java读取文件内容到byte[]数组中
- java里面byte数组和String字符串怎么转换