FileUtils.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. package com.goafanti.common.utils;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.io.PrintWriter;
  8. import java.io.UnsupportedEncodingException;
  9. import java.net.URLEncoder;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import java.util.regex.Pattern;
  13. import javax.servlet.http.HttpServletResponse;
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  15. import org.apache.poi.ss.usermodel.Cell;
  16. import org.apache.poi.ss.usermodel.CellType;
  17. import org.apache.poi.ss.usermodel.Row;
  18. import org.apache.poi.ss.usermodel.Sheet;
  19. import org.apache.poi.ss.usermodel.Workbook;
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.web.multipart.MultipartFile;
  23. import com.goafanti.achievement.bo.InputAchievement;
  24. import com.goafanti.common.bo.Error;
  25. import com.goafanti.common.error.BusinessException;
  26. public class FileUtils {
  27. @Value(value = "${upload.private.path}")
  28. private String uploadPrivatePath = null;
  29. private static final Pattern SLASH_PATTERN = Pattern.compile("^/|/$");
  30. private static final String SLASH = "/";
  31. private static final String UNDERLINE = "_";
  32. /**
  33. * response 输出JSON
  34. *
  35. * @param hresponse
  36. * @param resultMap
  37. * @throws IOException
  38. */
  39. public static void out(HttpServletResponse response, String jsonStr) {
  40. PrintWriter out = null;
  41. try {
  42. response.setHeader("Content-Type", "application/json");
  43. response.setCharacterEncoding("UTF-8");
  44. out = response.getWriter();
  45. out.println(jsonStr);
  46. } catch (Exception e) {
  47. LoggerUtils.fmtError(FileUtils.class, e, "输出数据失败");
  48. } finally {
  49. if (null != out) {
  50. out.flush();
  51. out.close();
  52. }
  53. }
  54. }
  55. /**
  56. * Excel报表导出
  57. *
  58. * @param response
  59. * @param fileName
  60. * @param workbook
  61. */
  62. public static void downloadExcel(HttpServletResponse response, String fileName, HSSFWorkbook workbook) {
  63. String fn = null;
  64. try {
  65. fn = URLEncoder.encode(fileName, "UTF-8");
  66. } catch (UnsupportedEncodingException e1) {
  67. fn = fileName;
  68. }
  69. response.setContentType("application/x-download;charset=UTF-8");
  70. response.setHeader("Content-Disposition", "attachment; filename=\"" + fn + "\";");
  71. OutputStream out = null;
  72. try {
  73. out = response.getOutputStream();
  74. workbook.write(out);
  75. } catch (IOException e) {
  76. LoggerUtils.fmtError(FileUtils.class, e, "输出Excel失败");
  77. } finally {
  78. if (null != out) {
  79. try {
  80. out.flush();
  81. out.close();
  82. } catch (IOException e) {
  83. out = null;
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * 根据上传文件 拼接fileName
  90. *
  91. * @param mf
  92. * @param isPrivate
  93. * @param sign
  94. * @param path
  95. * @return
  96. */
  97. public static String mosaicFileName(MultipartFile mf, boolean isPrivate, String sign, String path, String uid) {
  98. String suffix = mf.getOriginalFilename().substring(mf.getOriginalFilename().lastIndexOf("."));
  99. boolean uniq = false;
  100. if (sign.indexOf("demand_picture") != -1|| sign.indexOf("achievement_picture") != -1 || sign.indexOf("user_picture")!=-1
  101. || sign.indexOf("jt_project_picture")!=-1 || sign.indexOf("jt_business_picture")!=-1 || sign.indexOf("honor_picture")!=-1
  102. || sign.indexOf("banners")!=-1|| sign.indexOf("head_portrait")!=-1 || sign.indexOf("video")!=-1 ||sign.indexOf("eventPlanning")!=-1 ) {
  103. uniq = true;
  104. }
  105. String fileName = "";
  106. if (isPrivate || StringUtils.isNotBlank(sign)) {
  107. if (uniq) {
  108. fileName = path + uid + "/" + System.nanoTime() + "_" + sign + suffix;
  109. } else {
  110. fileName = path + uid + "/" + sign + suffix;
  111. }
  112. } else {
  113. fileName = path + uid + "/" + System.nanoTime() + suffix;
  114. }
  115. return fileName;
  116. }
  117. public static String mosaicFileName( String fn, boolean isPrivate, String path, String uid) {
  118. String fileName = "";
  119. if (isPrivate) {
  120. fileName = path + uid + "/" + fn;
  121. } else {
  122. fileName = path + uid + "/" + "logo" + fn ;
  123. }
  124. return fileName;
  125. }
  126. /**
  127. * 获取下载文件名称
  128. *
  129. * @param path
  130. * @return
  131. */
  132. public static String getDownloadFileName(String path) {
  133. if (StringUtils.isBlank(path) || path.lastIndexOf(".") < 0) {
  134. return null;
  135. }
  136. String prefix = "附件";
  137. String suffix = path.substring(path.lastIndexOf("."));
  138. return prefix + suffix;
  139. }
  140. public static String getSuffix(String path) {
  141. if (StringUtils.isBlank(path) || path.lastIndexOf(".") < 0) {
  142. return "";
  143. }
  144. return path.substring(path.lastIndexOf("."));
  145. }
  146. /**
  147. * 拼接文件路径
  148. *
  149. * @param root
  150. * @param params
  151. * @return
  152. */
  153. public static String buildFilePath(String... params) {
  154. StringBuilder sb = new StringBuilder();
  155. if (params != null) {
  156. for (String s : params) {
  157. sb.append(SLASH);
  158. sb.append(SLASH_PATTERN.matcher(s).replaceAll(""));
  159. }
  160. }
  161. return sb.toString();
  162. }
  163. /**
  164. * 拼接文件名字
  165. *
  166. * @param root
  167. * @param params
  168. * @return
  169. */
  170. public static String buildFileName(String... params) {
  171. return StringUtils.join(params, UNDERLINE);
  172. }
  173. // year
  174. private static String subStr(String s) {
  175. return "企业" + s.substring(s.lastIndexOf(UNDERLINE) + 1, s.lastIndexOf("."));
  176. }
  177. public static boolean deleteFile(String realFilePath) {
  178. return new File(realFilePath).delete();
  179. }
  180. /**
  181. *
  182. * @param response
  183. * @param fileName
  184. * @param realFilePath
  185. */
  186. public static void downloadFile(HttpServletResponse response, String fileName, String realFilePath) {
  187. InputStream in = null;
  188. OutputStream out = null;
  189. byte[] buffer = new byte[8 * 1024];
  190. try {
  191. File file = new File(realFilePath);
  192. in = new FileInputStream(file);
  193. out = response.getOutputStream();
  194. // 设置文件MIME类型
  195. response.setContentType("application/octet-stream");
  196. fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
  197. response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
  198. response.setHeader("Content-Length", String.valueOf(file.length()));
  199. for (;;) {
  200. int bytes = in.read(buffer);
  201. if (bytes == -1) {
  202. break;
  203. }
  204. out.write(buffer, 0, bytes);
  205. }
  206. } catch (IOException e) {
  207. LoggerUtils.fmtError(FileUtils.class, e, "IO错误:%s", e.getMessage());
  208. } finally {
  209. try {
  210. if (in != null) {
  211. in.close();
  212. }
  213. } catch (IOException e) {
  214. in = null;
  215. LoggerUtils.fmtError(FileUtils.class, e, "IO错误:%s", e.getMessage());
  216. }
  217. try {
  218. if (out != null) {
  219. out.close();
  220. }
  221. } catch (IOException e) {
  222. out = null;
  223. LoggerUtils.fmtError(FileUtils.class, e, "IO错误:%s", e.getMessage());
  224. }
  225. }
  226. }
  227. public static Workbook getWorkBook(MultipartFile file) {
  228. //创建Workbook工作薄对象,表示整个excel
  229. Workbook workbook = null;
  230. try {
  231. //获取excel文件的io流
  232. InputStream is = file.getInputStream();
  233. //如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
  234. if(file.getOriginalFilename().matches("^.+\\.(?i)(xls)$"))workbook = new HSSFWorkbook(is);
  235. if(file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$"))workbook = new XSSFWorkbook(is);
  236. } catch (IOException e) {
  237. }
  238. return workbook;
  239. }
  240. public static Sheet pushReadFile(MultipartFile file) {
  241. //获得Workbook工作薄对象
  242. Workbook workbook = getWorkBook(file);
  243. Sheet sheet=null;
  244. if(workbook != null){
  245. //获得当前sheet工作表
  246. sheet = workbook.getSheetAt(0);
  247. if(sheet == null){
  248. throw new BusinessException(new Error("未找到正确的参数。"));
  249. }
  250. }
  251. return sheet;
  252. }
  253. public static int rowDispose(Sheet sheet, int firstRowNum) {
  254. int lastRowNum=sheet.getLastRowNum();
  255. //处理空白行
  256. for (int i = firstRowNum; i <= sheet.getLastRowNum();i++) {
  257. Row r = sheet.getRow(i);
  258. if(r == null){
  259. // 如果是空行(即没有任何数据、格式),直接把它以下的数据往上移动
  260. sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
  261. continue;
  262. }
  263. boolean flag = false;
  264. for(Cell c:r){
  265. if(c.getCellTypeEnum() != CellType.BLANK){
  266. flag = true;
  267. break;
  268. }
  269. }
  270. if(flag){
  271. i++;
  272. continue;
  273. } else{
  274. //如果是空白行(即可能没有数据,但是有一定格式)
  275. if(i == sheet.getLastRowNum())//如果到了最后一行,直接将那一行remove掉
  276. sheet.removeRow(r);
  277. else//如果还没到最后一行,则数据往上移一行
  278. sheet.shiftRows(i+1, sheet.getLastRowNum(),-1);
  279. }
  280. }
  281. if (lastRowNum<2) {
  282. throw new BusinessException(new Error("未找到正确的参数。"));
  283. }
  284. return sheet.getLastRowNum();
  285. }
  286. public static int rowDisposeNotBlank(Sheet sheet, int firstRowNum) {
  287. int lastRowNum=sheet.getLastRowNum();
  288. //行数从0开始 默认使用2行做头部,则设置1
  289. int i=1;
  290. for(int rowNum = firstRowNum+2;rowNum <= lastRowNum;rowNum++){
  291. Row row = sheet.getRow(rowNum);
  292. if(row == null){
  293. continue;
  294. }
  295. Cell cell = row.getCell(0);
  296. String str =FileUtils.getCellValue(cell);
  297. if (StringUtils.isNotBlank(str)) {
  298. i++;
  299. }
  300. }
  301. if (i<2) {
  302. throw new BusinessException(new Error("未找到正确的参数。"));
  303. }
  304. return i;
  305. }
  306. public static String getCellValue(Cell cell){
  307. String cellValue = "";
  308. if(cell == null){
  309. return cellValue;
  310. }
  311. //把数字当成String来读,避免出现1读成1.0的情况
  312. if(cell.getCellTypeEnum() == CellType.NUMERIC){
  313. cell.setCellType(CellType.STRING);
  314. }
  315. //判断数据的类型
  316. switch (cell.getCellTypeEnum()){
  317. case NUMERIC: //数字
  318. cellValue = String.valueOf(cell.getNumericCellValue());
  319. break;
  320. case STRING: //字符串
  321. cellValue = String.valueOf(cell.getStringCellValue());
  322. break;
  323. case BOOLEAN: //Boolean
  324. cellValue = String.valueOf(cell.getBooleanCellValue());
  325. break;
  326. case FORMULA: //公式
  327. cellValue = String.valueOf(cell.getCellFormula());
  328. break;
  329. case BLANK: //空值
  330. cellValue = "";
  331. break;
  332. case ERROR: //故障
  333. cellValue = "非法字符";
  334. break;
  335. default:
  336. cellValue = "未知类型";
  337. break;
  338. }
  339. return cellValue;
  340. }
  341. }