FileUtil.java 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.nosum.common.util;
  2. import java.io.*;
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.util.UUID;
  6. /**
  7. * @Author:sumbytes
  8. * @Date:2018/09/27 12:52
  9. */
  10. public class FileUtil {
  11. /**
  12. * 获取文件后缀名
  13. */
  14. public static String getSuffix(String fileName) {
  15. int pos = fileName.lastIndexOf(".");
  16. if (pos == -1) {
  17. return ".png";
  18. }
  19. return fileName.substring(pos);
  20. }
  21. public static String createSingleFilePath(String parentPath, String fileName) {
  22. return parentPath + createSingleFileName(fileName);
  23. }
  24. /**
  25. * 根据原有文件名称,生成一个随机文件名称
  26. */
  27. public static String createSingleFileName(String fileName) { // 创建文件名称
  28. return UUID.randomUUID() + getSuffix(fileName);
  29. }
  30. /**
  31. * 根据文件路径将文件转为字节数组
  32. * @param filePath 文件路径
  33. * @return 字节数组
  34. */
  35. public static byte[] tranToBytes(String filePath) {
  36. byte[] data = null;
  37. URL url = null;
  38. InputStream input = null;
  39. ByteArrayOutputStream output=null;
  40. try{
  41. url = new URL(filePath);
  42. HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
  43. httpUrl.connect();
  44. httpUrl.getInputStream();
  45. input = httpUrl.getInputStream();
  46. output = new ByteArrayOutputStream();
  47. byte[] buf = new byte[1024];
  48. int numBytesRead = 0;
  49. while ((numBytesRead = input.read(buf)) != -1) {
  50. output.write(buf, 0, numBytesRead);
  51. }
  52. data = output.toByteArray();
  53. }catch (IOException e){
  54. e.printStackTrace();
  55. }finally {
  56. if (output!=null){ try { output.close(); } catch (IOException e) { e.printStackTrace(); } }
  57. if (input!=null){ try { input.close(); } catch (IOException e) { e.printStackTrace(); } }
  58. }
  59. return data;
  60. }
  61. }