java File和Byte[]数组 相互转换

  1. public class Test {
  2. public static void main(String[] args){
  3. String filePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src\\1.docx";
  4. String outFilePath = "E:\\softoon\\workspace_softoon\\TestMobile\\src";
  5. String outFileName = "2.docx";
  6. getFile(getBytes(filePath),outFilePath,outFileName);
  7. }
  8. // ----------------获得指定文件的byte数组 ----------------
  9. public static byte[] getBytes(String filePath){
  10. byte[] buffer = null;
  11. try {
  12. File file = new File(filePath);
  13. FileInputStream fis = new FileInputStream(file);
  14. ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
  15. byte[] b = new byte[1000];
  16. int n;
  17. while ((n = fis.read(b)) != -1) {
  18. bos.write(b, 0, n);
  19. }
  20. fis.close();
  21. bos.close();
  22. buffer = bos.toByteArray();
  23. } catch (FileNotFoundException e) {
  24. e.printStackTrace();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. return buffer;
  29. }
  30. // ----------------根据byte数组,生成文件 ----------------
  31. public static void getFile(byte[] bfile, String filePath,String fileName) {
  32. BufferedOutputStream bos = null;
  33. FileOutputStream fos = null;
  34. File file = null;
  35. try {
  36. File dir = new File(filePath);
  37. if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
  38. dir.mkdirs();
  39. }
  40. file = new File(filePath+"\\"+fileName);
  41. fos = new FileOutputStream(file);
  42. bos = new BufferedOutputStream(fos);
  43. bos.write(bfile);
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. } finally {
  47. if (bos != null) {
  48. try {
  49. bos.close();
  50. } catch (IOException e1) {
  51. e1.printStackTrace();
  52. }
  53. }
  54. if (fos != null) {
  55. try {
  56. fos.close();
  57. } catch (IOException e1) {
  58. e1.printStackTrace();
  59. }
  60. }
  61. }
  62. }
  63. }


posted @ 2017-06-10 21:06  edgedance  阅读(11926)  评论(0编辑  收藏  举报