FileUtils.java 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. package com.iamberry.wechat.file;
  2. import java.io.*;
  3. import java.security.SecureRandom;
  4. import java.util.Date;
  5. import java.util.UUID;
  6. import javax.servlet.ServletContext;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import com.iamberry.wechat.tools.DateTimeUtil;
  9. /**
  10. * @company 深圳爱贝源科技有限公司
  11. * @website www.iamberry.com
  12. * @author 献
  13. * @tel 18271840547
  14. * @date 2016年10月13日
  15. * @explain 上传文件工具类
  16. */
  17. public class FileUtils {
  18. /**
  19. * 保存文件到项目根目录下指定路径
  20. * @param servletContext 使用request.getServletContext() 获取<br>
  21. * @param file 文件路径<br>
  22. * @param savePathStr 项目根目录下,必须以'/'结尾,如:'/aa/bb/cc/'<br>
  23. * @return 返回UploadResultBean<br>
  24. * @throws Exception 异常
  25. */
  26. public static UploadResultBean saveFile(ServletContext servletContext, MultipartFile file, String savePathStr) {
  27. // 检查&获取原文件名称
  28. if (file.getOriginalFilename() == null || file.isEmpty()) {
  29. return null;
  30. }
  31. String imageName = file.getOriginalFilename();
  32. if (imageName == null || imageName.isEmpty()) {
  33. return null;
  34. }
  35. // 返回对象
  36. UploadResultBean bean = new UploadResultBean();
  37. bean.setUploadFileName(imageName);
  38. // 获取文件后缀
  39. FileType fileType = null;
  40. try {
  41. fileType = getType(file.getInputStream());
  42. } catch (IOException e1) {
  43. return null;
  44. }
  45. if (fileType == null) {
  46. return null;
  47. }
  48. // 文件名称 时间+随机数.后缀名
  49. StringBuilder fileName = new StringBuilder();
  50. fileName.append(DateTimeUtil.format(new Date(), "yyMMddHHmmss"))
  51. .append(byte2hex(createRandomByte())).append(".").append(fileType.getSuffix());
  52. bean.setSaveFileName(fileName.toString());
  53. bean.setSaveFilePath(savePathStr + fileName.toString());
  54. // URL路径
  55. String savePath = servletContext.getRealPath(savePathStr);
  56. // 文件系统路径
  57. savePath = savePath + File.separator + fileName.toString();
  58. try {
  59. org.apache.commons.io.FileUtils.writeByteArrayToFile(new File(savePath), file.getBytes());
  60. } catch (IOException e) {
  61. return null;
  62. }
  63. bean.setFile(savePath);
  64. // 关闭相关流对象
  65. return bean;
  66. }
  67. /**
  68. * 创建一个安全的随机数组byte[]
  69. *
  70. * @return
  71. */
  72. private static byte[] createRandomByte() {
  73. try {
  74. SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
  75. byte[] bytes = new byte[1024 / 8];
  76. random.nextBytes(bytes);
  77. int count = 10;
  78. byte[] seed = random.generateSeed(count);
  79. random = SecureRandom.getInstance("SHA1PRNG");
  80. random.setSeed(seed);
  81. SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");
  82. random2.setSeed(seed);
  83. return seed;
  84. } catch (Exception e) {
  85. return UUID.randomUUID().toString().getBytes();
  86. }
  87. }
  88. /**
  89. * 读取文件头,这里需要注意的是,每个文件的魔数的长度都不相同,由此使用startWith
  90. * @param filePath
  91. * @return
  92. * @throws Exception
  93. */
  94. public static String getFileHeader(InputStream inputStream) throws Exception {
  95. byte [] b = new byte[28];
  96. inputStream.read(b, 0, 28);
  97. // 此处可以不关,但是掉用方,必须关闭流对象
  98. inputStream.close();
  99. return byte2hex(b);
  100. }
  101. /**
  102. * java字节码转字符串
  103. * @param b
  104. * @return
  105. */
  106. public static String byte2hex(byte[] b) { //一个字节的数,
  107. // 转成16进制字符串
  108. String hs = "";
  109. String tmp = "";
  110. for (int n = 0; n < b.length; n++) {
  111. //整数转成十六进制表示
  112. tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
  113. if (tmp.length() == 1) {
  114. hs = hs + "0" + tmp;
  115. } else {
  116. hs = hs + tmp;
  117. }
  118. }
  119. tmp = null;
  120. return hs;
  121. }
  122. /**
  123. * 判断文件类型
  124. * @throws Exception
  125. */
  126. public static FileType getType(InputStream inputStream) {
  127. String fileHead = null;
  128. try {
  129. fileHead = getFileHeader(inputStream);
  130. } catch (Exception e) {
  131. // TODO Auto-generated catch block
  132. e.printStackTrace();
  133. }
  134. if (fileHead == null || fileHead.length() == 0) {
  135. return null;
  136. }
  137. // 大写,因为在我们的FileType中,全部使用了大写
  138. fileHead = fileHead.toUpperCase();
  139. FileType [] fileTypes = FileType.values();
  140. for (FileType fileType : fileTypes) {
  141. if (fileHead.startsWith(fileType.getValue())) {
  142. return fileType;
  143. }
  144. }
  145. return null;
  146. }
  147. /**复制文件的方法*/
  148. public static void copyFile(String oldPath, String newPath) {
  149. try {
  150. int bytesum = 0;
  151. int byteread = 0;
  152. File oldfile = new File(oldPath);
  153. if (oldfile.exists()) { //文件存在时
  154. InputStream inStream = new FileInputStream(oldPath); //读入原文件
  155. FileOutputStream fs = new FileOutputStream(newPath);
  156. byte[] buffer = new byte[1444];
  157. while ((byteread = inStream.read(buffer)) != -1) {
  158. bytesum += byteread; //字节数 文件大小
  159. fs.write(buffer, 0, byteread);
  160. }
  161. inStream.close();
  162. fs.close();
  163. }
  164. } catch (Exception e) {
  165. System.out.println("复制单个文件操作出错");
  166. e.printStackTrace();
  167. }
  168. }
  169. }