FileExposeUtil.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. package com.behosoft.util;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.io.OutputStreamWriter;
  11. import java.io.PrintStream;
  12. import java.io.PrintWriter;
  13. import java.io.RandomAccessFile;
  14. import java.text.SimpleDateFormat;
  15. import java.util.ArrayList;
  16. import java.util.Arrays;
  17. import java.util.Calendar;
  18. import java.util.Date;
  19. import java.util.List;
  20. import javax.servlet.ServletOutputStream;
  21. import javax.servlet.http.HttpServletResponse;
  22. import com.behosoft.framework.web.exception.CommonException;
  23. public class FileExposeUtil {
  24. /**
  25. * 获取classpath的根目录
  26. *
  27. * @return
  28. */
  29. public static String getRootClasspath() {
  30. String path = FileExposeUtil.class.getResource("/").getPath();
  31. // if (AppContextUtils.getServletContext() != null
  32. // && (AppContextUtils.getServletContext().getServerInfo()
  33. // .startsWith(GlobalConstants.SERVER_KEY_WEBSPHERE) || AppContextUtils.getServletContext()
  34. // .getServerInfo().startsWith("Apusic Application Server"))) {
  35. //
  36. // }
  37. // 兼容 Apusic Application Server
  38. if (path.indexOf("/WEB-INF/classes/") == -1) {
  39. String tmpPath = FileExposeUtil.class.getResource("").getPath().replaceAll("%20", " ");
  40. path = tmpPath.substring(0, tmpPath.indexOf("/WEB-INF/classes/") + "/WEB-INF/classes/".length());
  41. }
  42. path = path.replaceAll("%20", " ");
  43. return path;
  44. }
  45. /**
  46. * 获取根据目录路径 绝对路径
  47. *
  48. * @return
  49. */
  50. public static String getRootPath() {
  51. String path = getRootClasspath();
  52. if (path.indexOf("WEB-INF") != -1) {
  53. path = path.substring(0, path.indexOf("WEB-INF"));
  54. }
  55. // comment below because of unix path
  56. // path = path.substring(1, path.length());
  57. return path;
  58. }
  59. /**
  60. * <p>
  61. * Description:checkFileExist
  62. * </p>
  63. *
  64. * @param filePath filePath
  65. * @return
  66. */
  67. public static boolean checkFileExist(String filePath) {
  68. File file = new File(filePath);
  69. return file.exists();
  70. }
  71. /**
  72. * 获取文件大小
  73. *
  74. * @return
  75. */
  76. public static long getFileSize(String filePath) {
  77. long ret = 0;
  78. File file = new File(filePath);
  79. if (file.exists()) {
  80. ret = file.length();
  81. }
  82. return ret;
  83. }
  84. /**
  85. * <p>
  86. * Description:[方法功能中文描述]
  87. * </p>
  88. *
  89. * @param buffer
  90. * @param filePath
  91. */
  92. public static void readToBuffer(StringBuffer buffer, String filePath) {
  93. // 先根据输入/输出文件生成相应的输入/输出流
  94. InputStream is = null;
  95. try {
  96. is = new FileInputStream(filePath);
  97. readToBuffer(buffer, is);
  98. }
  99. catch (IOException e) {
  100. throw new CommonException("common.read.file.error");
  101. }
  102. finally {
  103. try {
  104. if (is != null) {
  105. is.close();
  106. }
  107. }
  108. catch (IOException e) {
  109. throw new CommonException("common.read.file.error");
  110. }
  111. }
  112. }
  113. /**
  114. * <p>
  115. * Description:将流中的文本读入一个 StringBuffer 中
  116. * </p>
  117. *
  118. * @param buffer buffer
  119. * @param is InputStream
  120. */
  121. public static void readToBuffer(StringBuffer buffer, InputStream is) {
  122. // 用来保存每行读取的内容
  123. String line;
  124. try {
  125. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  126. // 读取第一行
  127. line = reader.readLine();
  128. // 如果 line 为空说明读完了
  129. while (line != null) {
  130. // 将读到的内容添加到 buffer 中
  131. buffer.append(line);
  132. // 添加换行符
  133. buffer.append("\n");
  134. // 读取下一行
  135. line = reader.readLine();
  136. }
  137. }
  138. catch (IOException e) {
  139. throw new CommonException("common.read.file.error");
  140. }
  141. }
  142. /**
  143. * <p>
  144. * Description:将 StringBuffer 中的内容读出到流中
  145. * </p>
  146. *
  147. * @param buffer StringBuffer
  148. * @param os OutputStream
  149. */
  150. public static void writeFromBuffer(StringBuffer buffer, OutputStream os) {
  151. PrintStream ps = new PrintStream(os);
  152. ps.print(buffer.toString());
  153. }
  154. /**
  155. * 22. 将 StringBuffer 中的内容读出到流中
  156. */
  157. public static void writeFromBuffer(StringBuffer buffer, String outPath) {
  158. OutputStream out = null;
  159. try {
  160. out = new FileOutputStream(outPath);
  161. writeFromBuffer(buffer, out);
  162. }
  163. catch (IOException e) {
  164. throw new CommonException("common.write.file.error");
  165. }
  166. }
  167. /**
  168. * 3*. 从输出流中拷贝内容到输入流中
  169. */
  170. private static void copyStream(InputStream is, OutputStream os) {
  171. byte[] bytes = new byte[1024];
  172. int i = -1;
  173. try {
  174. while ((i = is.read(bytes)) != -1) {
  175. os.write(bytes, 0, i);
  176. }
  177. os.flush();
  178. }
  179. catch (IOException e) {
  180. throw new CommonException("common.copy.file.error");
  181. }
  182. }
  183. /**
  184. * 4. 调用 (orgFilePath, outFilePath) 方法拷贝文本文件
  185. *
  186. * @param orgFilePath 原文件路径,包含文件名
  187. * @param outFilePath 拷贝文件路径,包含文件名
  188. */
  189. public static void copyFile(String orgFilePath, String outFilePath) {
  190. // 先根据输入/输出文件生成相应的输入/输出流
  191. InputStream is = null;
  192. OutputStream os = null;
  193. try {
  194. createFile(outFilePath);
  195. is = new FileInputStream(orgFilePath);
  196. os = new FileOutputStream(outFilePath);
  197. copyStream(is, os); // 用 copyStream 拷贝内容
  198. os.flush();
  199. }
  200. catch (Exception e) {
  201. throw new CommonException("common.copy.file.error");
  202. }
  203. finally {
  204. try {
  205. if (is != null)
  206. is.close();
  207. }
  208. catch (Exception e) {
  209. throw new CommonException("common.copy.file.error");
  210. }
  211. try {
  212. if (os != null)
  213. os.close();
  214. }
  215. catch (Exception e) {
  216. throw new CommonException("common.copy.file.error");
  217. }
  218. }
  219. }
  220. /**
  221. * 4. 调用 (orgFilePath, outFilePath) 方法拷贝文本文件
  222. *
  223. * @param orgFilePath 原文件路径,包含文件名
  224. * @param outFilePath 拷贝文件路径,包含文件名
  225. */
  226. public static void copyFile(File file, String outFilePath) {
  227. // 先根据输入/输出文件生成相应的输入/输出流
  228. InputStream is = null;
  229. OutputStream os = null;
  230. try {
  231. createFile(outFilePath);
  232. is = new FileInputStream(file);
  233. os = new FileOutputStream(outFilePath);
  234. copyStream(is, os); // 用 copyStream 拷贝内容
  235. os.flush();
  236. }
  237. catch (Exception e) {
  238. throw new CommonException("common.copy.file.error");
  239. }
  240. finally {
  241. try {
  242. if (is != null)
  243. is.close();
  244. }
  245. catch (Exception e) {
  246. throw new CommonException("common.copy.file.error");
  247. }
  248. try {
  249. if (os != null)
  250. os.close();
  251. }
  252. catch (Exception e) {
  253. throw new CommonException("common.copy.file.error");
  254. }
  255. }
  256. }
  257. /**
  258. * 5. 调用 (orgFilePath, outFilePath) 方法拷贝文本文件
  259. *
  260. * @param orgFilePath 原文件路径,包含文件名
  261. * @param outFilePath 拷贝文件路径,包含文件名
  262. */
  263. public static void copyFile(String orgFilePath, String outFileRootPath, String aimFileName) {
  264. // 先根据输入/输出文件生成相应的输入/输出流
  265. createFile(outFileRootPath, aimFileName);
  266. copyFile(orgFilePath, outFileRootPath + aimFileName);
  267. }
  268. /**
  269. * 创建文件或者文件夹
  270. *
  271. * @param filePath
  272. */
  273. public static void createFile(String filePath) {
  274. if (filePath != null && !"".equals(filePath) && !checkFileExist(filePath)) {
  275. File file = null;
  276. try {
  277. if (filePath.indexOf(".") != -1) {
  278. filePath = filePath.replace('\\', '/');
  279. String temp = filePath.substring(0, filePath.lastIndexOf("/") + 1);
  280. if (checkFileExist(temp)) {
  281. file = new File(filePath);
  282. file.createNewFile();
  283. }
  284. else {
  285. file = new File(temp);
  286. file.mkdirs();
  287. file = new File(filePath);
  288. file.createNewFile();
  289. }
  290. }
  291. else {
  292. file = new File(filePath);
  293. file.mkdirs();
  294. }
  295. }
  296. catch (IOException e) {
  297. throw new CommonException("common.create.file.error");
  298. }
  299. }
  300. }
  301. /**
  302. * 7*. 把流保存到本地文件(路径和文件名分开)
  303. *
  304. * @param is
  305. * @param filePath
  306. * @param fileName
  307. */
  308. public static void saveFile(InputStream is, String filePath, String fileName, boolean isBinary) {
  309. File file = new File(filePath);
  310. if (!file.exists()) {
  311. file.mkdirs();
  312. }
  313. OutputStream os = null;
  314. PrintWriter writer = null;
  315. BufferedReader reader = null;
  316. try {
  317. os = new FileOutputStream(filePath + "\\" + fileName);
  318. if (isBinary) {
  319. int len;
  320. byte[] buf = new byte[1024];
  321. while ((len = is.read(buf, 0, 1024)) != -1) {
  322. os.write(buf, 0, len);
  323. }
  324. os.flush();
  325. }
  326. else {
  327. String line;
  328. reader = new BufferedReader(new InputStreamReader(is));
  329. writer = new PrintWriter(new OutputStreamWriter(os));
  330. line = reader.readLine();
  331. while (line != null) {
  332. writer.println(line);
  333. line = reader.readLine();
  334. }
  335. writer.flush();
  336. }
  337. }
  338. catch (IOException e) {
  339. throw new CommonException("common.save.file.error");
  340. }
  341. finally {
  342. try {
  343. if (os != null) {
  344. os.close();
  345. }
  346. }
  347. catch (IOException e) {
  348. throw new CommonException("common.save.file.error");
  349. }
  350. try {
  351. if (writer != null) {
  352. writer.close();
  353. }
  354. }
  355. catch (Exception e) {
  356. throw new CommonException("common.save.file.error");
  357. }
  358. try {
  359. if (reader != null) {
  360. reader.close();
  361. }
  362. }
  363. catch (Exception e) {
  364. throw new CommonException("common.save.file.error");
  365. }
  366. }
  367. }
  368. /**
  369. * 7*. 把流保存到本地文件(路径包含文件名)
  370. *
  371. * @param is
  372. * @param filePath
  373. * @param fileName
  374. * @throws IOException
  375. */
  376. public static void saveFile(InputStream is, String filePath) {
  377. int dirStrLoc = filePath.lastIndexOf("\\");
  378. if (dirStrLoc < 0) {
  379. dirStrLoc = filePath.lastIndexOf("/");
  380. }
  381. if (dirStrLoc > 1) {
  382. File file = new File(filePath.substring(0, dirStrLoc));
  383. if (!file.exists()) {
  384. file.mkdirs();
  385. }
  386. }
  387. OutputStream os = null;
  388. PrintWriter writer = null;
  389. BufferedReader reader = null;
  390. try {
  391. os = new FileOutputStream(filePath);
  392. String line;
  393. reader = new BufferedReader(new InputStreamReader(is));
  394. writer = new PrintWriter(new OutputStreamWriter(os));
  395. line = reader.readLine();
  396. while (line != null) {
  397. writer.println(line);
  398. line = reader.readLine();
  399. }
  400. writer.flush();
  401. }
  402. catch (Exception e) {
  403. throw new CommonException("common.save.file.error");
  404. }
  405. finally {
  406. try {
  407. if (os != null) {
  408. os.close();
  409. }
  410. }
  411. catch (Exception e) {
  412. throw new CommonException("common.save.file.error");
  413. }
  414. try {
  415. if (writer != null) {
  416. writer.close();
  417. }
  418. }
  419. catch (Exception e) {
  420. throw new CommonException("common.save.file.error");
  421. }
  422. try {
  423. if (reader != null) {
  424. reader.close();
  425. }
  426. }
  427. catch (Exception e) {
  428. throw new CommonException("common.save.file.error");
  429. }
  430. }
  431. }
  432. /**
  433. * 5. 替文本中特殊字符
  434. *
  435. * @param filePath 文件路径,包含文件名
  436. * @param
  437. */
  438. public static void replaceChar(String filePath, String[] oldChar, String[] newChar) {
  439. // 先根据输入/输出文件生成相应的输入/输出流
  440. InputStream is = null;
  441. OutputStream out = null;
  442. try {
  443. is = new FileInputStream(filePath);
  444. StringBuffer buffer = new StringBuffer();
  445. readToBuffer(buffer, is);
  446. String textContent = buffer.toString();
  447. // 替换开始
  448. if (oldChar != null && newChar != null && (oldChar.length == newChar.length)) {
  449. for (int i = 0; i < oldChar.length; i++) {
  450. textContent = textContent.replaceAll(oldChar[i], newChar[i]);
  451. }
  452. }
  453. buffer.delete(0, buffer.length());
  454. buffer.append(textContent);
  455. out = new FileOutputStream(filePath);
  456. writeFromBuffer(buffer, out);
  457. out.flush();
  458. }
  459. catch (Exception e) {
  460. throw new CommonException("common.write.file.error");
  461. }
  462. finally {
  463. try {
  464. if (is != null)
  465. is.close();
  466. }
  467. catch (Exception e) {
  468. throw new CommonException("common.write.file.error");
  469. }
  470. try {
  471. if (out != null)
  472. out.close();
  473. }
  474. catch (Exception e) {
  475. throw new CommonException("common.write.file.error");
  476. }
  477. }
  478. }
  479. /**
  480. * 删除给定文件
  481. *
  482. * @param path
  483. */
  484. public static void delFile(String path) {
  485. File file = new File(path);
  486. if (file.exists()) {
  487. file.delete();
  488. }
  489. }
  490. /**
  491. * 删除给定文件
  492. *
  493. * @param path
  494. */
  495. public static void delFile(File file) {
  496. if (file.exists()) {
  497. file.delete();
  498. }
  499. }
  500. /**
  501. * 功能:删除文件夹方法
  502. *
  503. * @param delPath 要删除的文件夹路径
  504. * @return true delete file success,false delete file faild
  505. */
  506. public static boolean deleteDirs(String delPath) throws Exception {
  507. return deleteDirs(new File(delPath));
  508. }
  509. /**
  510. * <p>
  511. * Description:删除文件夹方法
  512. * </p>
  513. *
  514. * @param delPath
  515. * @param l 如果文件生成时间与现在时间的差大于l则删除
  516. * @return
  517. * @throws Exception
  518. */
  519. public static boolean deleteDirs(String delPath, long l) throws Exception {
  520. return deleteDirs(new File(delPath), l);
  521. }
  522. /**
  523. * 功能:删除文件夹方法
  524. *
  525. * @param dir 要删除的文件夹路径(java.io.File类型)
  526. * @return true delete file success,false delete file faild
  527. */
  528. public static boolean deleteDirs(File dir) {
  529. boolean delSuccess = false;
  530. File m_root = dir;
  531. List<File> m_dirs = new ArrayList<File>();
  532. if (!m_root.isDirectory()) { // 判断输入的是否为路径
  533. if (m_root.exists() && m_root.canWrite()) {// 如果文件存在就删除
  534. m_root.delete();
  535. delSuccess = true;
  536. }
  537. }
  538. else {
  539. m_dirs.add(m_root);
  540. findFile(m_root, m_dirs); // 获取指定路径下的所有文件已经文件夹(递归调用)
  541. rootDelete(m_dirs); // 删除list中的所有文件(倒叙循环删除)
  542. delSuccess = true;
  543. }
  544. return delSuccess;
  545. }
  546. /**
  547. * <p>
  548. * Description:[方法功能中文描述]
  549. * </p>
  550. *
  551. * @param dir
  552. * @param l 如果文件生成时间与现在时间的差大于l则删除
  553. * @return
  554. */
  555. public static boolean deleteDirs(File dir, long l) {
  556. boolean delSuccess = false;
  557. File m_root = dir;
  558. List<File> m_dirs = new ArrayList<File>();
  559. if (!m_root.isDirectory()) { // 判断输入的是否为路径
  560. if (m_root.exists() && m_root.canWrite() && (new Date().getTime() - m_root.lastModified()) > l) {// 如果文件存在就删除
  561. try {
  562. m_root.delete();
  563. }
  564. catch (Exception e) {
  565. }
  566. delSuccess = true;
  567. }
  568. }
  569. else {
  570. m_dirs.add(m_root);
  571. try {
  572. findFile(m_root, m_dirs); // 获取指定路径下的所有文件已经文件夹(递归调用)
  573. rootDelete(m_dirs, l); // 删除list中的所有文件(倒叙循环删除)
  574. }
  575. catch (Exception e) {
  576. throw new CommonException("common.delete.file.error");
  577. }
  578. delSuccess = true;
  579. }
  580. return delSuccess;
  581. }
  582. /**
  583. * 功能:删除文件或文件夹 注意:使用倒叙删除,先删除文件,然后删除空文件夹
  584. */
  585. private static void rootDelete(List<File> m_dirs) {
  586. if (m_dirs != null && m_dirs.size() > 0) {
  587. // 使用倒叙循环删除(先删除文件,再删除文件夹)
  588. for (int i = m_dirs.size() - 1; i >= 0; i--) {
  589. File f = m_dirs.remove(i);// 获取之后删除list中的数据
  590. // 删除数据
  591. if (f.exists() && f.canWrite()) {
  592. f.delete();
  593. }
  594. }
  595. }
  596. else {
  597. throw new CommonException("common.delete.file.error");
  598. }
  599. }
  600. /**
  601. * <p>
  602. * Description:[方法功能中文描述]
  603. * </p>
  604. *
  605. * @param m_dirs
  606. * @param l 如果文件生成时间与现在时间的差大于l则删除
  607. */
  608. private static void rootDelete(List<File> m_dirs, long l) {
  609. if (m_dirs != null && m_dirs.size() > 0) {
  610. // 使用倒叙循环删除(先删除文件,再删除文件夹)
  611. for (int i = m_dirs.size() - 1; i >= 0; i--) {
  612. File f = m_dirs.remove(i);// 获取之后删除list中的数据
  613. // 删除数据
  614. if (f.exists() && f.canWrite() && (new Date().getTime() - f.lastModified()) > l) {
  615. f.delete();
  616. }
  617. }
  618. }
  619. else {
  620. throw new CommonException("common.delete.file.error");
  621. }
  622. }
  623. /**
  624. * 功能:获取所有文件和文件夹,存储在m_dirs中 注意:递归调用
  625. *
  626. * @param tempRoot 文件路径
  627. */
  628. public static void findFile(File tempRoot, List<File> m_dirs) {
  629. findFile(tempRoot, m_dirs, null);
  630. }
  631. /**
  632. * 功能:获取给定文件类型的所有文件,存储在m_dirs中 注意:递归调用
  633. *
  634. * @param tempRoot 文件路径
  635. */
  636. public static void findFile(File tempRoot, List<File> m_dirs, String suffix) {
  637. // 获取指定路径下的所有文件
  638. File[] dirs = tempRoot.listFiles();
  639. if (dirs != null) {
  640. // 将文件数组转换成List对象
  641. List<File> dirslist = Arrays.asList(dirs);
  642. if (suffix == null)
  643. m_dirs.add(tempRoot);
  644. // 递归调用
  645. for (int i = 0; i < dirslist.size(); i++) {
  646. findFile(dirslist.get(i), m_dirs, suffix);
  647. }
  648. }
  649. else {
  650. String name = tempRoot.getName();
  651. if (suffix != null) {
  652. name = name.substring(name.lastIndexOf(".") + 1);
  653. if (suffix.equals(name)) {
  654. m_dirs.add(tempRoot);
  655. }
  656. }
  657. else {
  658. m_dirs.add(tempRoot);
  659. }
  660. }
  661. }
  662. /**
  663. * 功能:检查文件是否存在 注意:递归调用
  664. *
  665. * @param tempRoot 文件路径
  666. */
  667. public static boolean checkFileExist(File tempRoot, String fileName) {
  668. boolean ret = false;
  669. // 获取指定路径下的所有文件
  670. File[] dirs = tempRoot.listFiles();
  671. if (dirs != null) {
  672. // 将文件数组转换成List对象
  673. List<File> dirslist = Arrays.asList(dirs);
  674. // 递归调用
  675. for (int i = 0; i < dirslist.size(); i++) {
  676. ret = checkFileExist(dirslist.get(i), fileName);
  677. if (ret) {
  678. break;
  679. }
  680. }
  681. }
  682. else {
  683. if (tempRoot.getName().trim().equals(fileName.trim())) {
  684. ret = true;
  685. }
  686. }
  687. return ret;
  688. }
  689. public static boolean checkFileExist(String dirRoot, String fileName) {
  690. boolean ret = false;
  691. try {
  692. File file = new File(dirRoot);
  693. ret = checkFileExist(file, fileName);
  694. }
  695. catch (Exception e) {
  696. throw new CommonException("common.check.file.error");
  697. }
  698. return ret;
  699. }
  700. /**
  701. * 功能:获取所有文件和文件夹,存储在m_dirs中
  702. *
  703. * @param rootPath 文件路径
  704. */
  705. public static void findFile(String rootPath, List<File> m_dirs) {
  706. File file = new File(rootPath);
  707. findFile(file, m_dirs);
  708. }
  709. /**
  710. * 功能:获取给定扩展名的所有文件,存储在m_dirs中
  711. *
  712. * @param rootPath 文件路径
  713. * @param m_dirs 存放文件
  714. * @param suffix 扩展名
  715. */
  716. public static void findFile(String rootPath, List<File> m_dirs, String suffix) {
  717. File file = new File(rootPath);
  718. findFile(file, m_dirs, suffix);
  719. }
  720. /**
  721. * 功能:获取所有文件和文件夹的绝对路径,存储在filePath中
  722. *
  723. * @param rootPath 文件路径
  724. */
  725. public static void findFilePath(String rootPath, List<String> filePath) throws Exception {
  726. File file = new File(rootPath);
  727. List<File> m_dirs = new ArrayList<File>();
  728. findFile(file, m_dirs);// 获取所有文件
  729. if (m_dirs != null && m_dirs.size() > 0) {
  730. int size = m_dirs.size();
  731. // 遍历所有文件,获取其绝对路径
  732. for (int i = 0; i < size; i++) {
  733. File f = m_dirs.get(i);
  734. filePath.add(f.getPath());
  735. }
  736. }
  737. }
  738. /**
  739. * 根据路径获取文件名称
  740. *
  741. * @param filePath
  742. * @return
  743. */
  744. public static String getFileName(String filePath) {
  745. String ret = "";
  746. filePath = filePath.replace("\\", "/");
  747. if (filePath.lastIndexOf("/") != -1) {
  748. ret = filePath.substring(filePath.lastIndexOf("/") + 1);
  749. }
  750. else {
  751. ret = filePath;
  752. }
  753. return ret;
  754. }
  755. public static void rename(String filepath, String oldName, String newName) {
  756. try {
  757. File source = new File(filepath + "\\" + oldName);
  758. File target = new File(filepath + "\\" + newName);
  759. source.renameTo(target);
  760. }
  761. catch (Exception e) {
  762. throw new CommonException("common.rename.file.error");
  763. }
  764. }
  765. public static void rename(String oldPath, String newPath) {
  766. try {
  767. File source = new File(oldPath);
  768. File target = new File(newPath);
  769. source.renameTo(target);
  770. }
  771. catch (Exception e) {
  772. throw new CommonException("common.rename.file.error");
  773. }
  774. }
  775. /**
  776. * 根据文件名称获取文件后缀
  777. *
  778. * @param filePath
  779. * @return
  780. */
  781. public static String getFileSuffix(String fileName) {
  782. String ret = "";
  783. if (fileName != null && fileName.indexOf(".") > 0) {
  784. ret = fileName.substring(fileName.indexOf("."), fileName.length());
  785. }
  786. return ret;
  787. }
  788. /**
  789. * 生成文件
  790. *
  791. * @param rootPath
  792. * @param fileName
  793. * @param fileSize
  794. * @return
  795. */
  796. public static File createFile(String rootPath, String fileName, Long fileSize) {
  797. File file = new File(rootPath);
  798. if (!file.exists()) {
  799. file.mkdirs();
  800. }
  801. file = new File(rootPath + "\\" + fileName);
  802. RandomAccessFile acessFile = null;
  803. try {
  804. acessFile = new RandomAccessFile(file, "rw");
  805. acessFile.setLength(fileSize.longValue());
  806. }
  807. catch (Exception e) {
  808. throw new CommonException("common.create.file.error");
  809. }
  810. finally {
  811. try {
  812. if (acessFile != null)
  813. acessFile.close();
  814. }
  815. catch (Exception e) {
  816. throw new CommonException("common.create.file.error");
  817. }
  818. }
  819. return file;
  820. }
  821. public static List<String> getFilenames(String filepath) {
  822. List<String> list = new ArrayList<String>();
  823. File directory = new File(filepath);
  824. File[] files = directory.listFiles();
  825. for (int i = 0; i < files.length; i++) {
  826. list.add(filepath + files[i].getName());
  827. }
  828. return list;
  829. }
  830. public static List<File> getFiles(String filepath) {
  831. List<File> list = new ArrayList<File>();
  832. File directory = new File(filepath);
  833. File[] files = directory.listFiles();
  834. for (int i = 0; i < files.length; i++) {
  835. list.add(files[i]);
  836. }
  837. return list;
  838. }
  839. /**
  840. * 生成文件
  841. *
  842. * @param rootPath
  843. * @param fileName
  844. * @param fileSize
  845. * @return
  846. */
  847. public static File createFile(String rootPath, String fileName) {
  848. return createFile(rootPath, fileName, new Long(0));
  849. }
  850. public static void downLoadFile(HttpServletResponse response, String downPath, String fileName, String targetfile) {
  851. ServletOutputStream os = null;
  852. try {
  853. File dFile = new File(downPath + fileName);
  854. if (dFile.exists()) {
  855. response.setContentType("application/octet-stream");
  856. response.setHeader("Content-Disposition", "filename=" + targetfile);
  857. os = response.getOutputStream();
  858. }
  859. else {
  860. throw new CommonException("common.find.no.file", new String[] { downPath + fileName });
  861. }
  862. String downLoadFile = downPath + fileName;
  863. // 下载文件的路径是否存在
  864. File downLoadPath = new File(downPath);
  865. if (!downLoadPath.exists()) {
  866. downLoadPath.mkdirs();
  867. }
  868. // 创建文件
  869. FileInputStream in = new FileInputStream(downLoadFile);
  870. int byteRead = 0;
  871. byte[] buffer = new byte[1024];
  872. while ((byteRead = in.read(buffer, 0, 1024)) != -1) {
  873. os.write(buffer, 0, byteRead);
  874. }
  875. os.flush();
  876. os.close();
  877. in.close();
  878. }
  879. catch (IOException e) {
  880. try {
  881. os.flush();
  882. os.close();
  883. }
  884. catch (IOException e1) {
  885. }
  886. throw new CommonException("");
  887. }
  888. }
  889. public static void downLoadFile(HttpServletResponse response, FileInputStream in, String targetfile) {
  890. ServletOutputStream os = null;
  891. try {
  892. // response.setCharacterEncoding("UTF-8");
  893. response.setContentType("application/x-msexcel");
  894. response.setHeader("Content-Disposition", "filename=" + targetfile);
  895. os = response.getOutputStream();
  896. // 创建文件
  897. int byteRead = 0;
  898. byte[] buffer = new byte[8192];
  899. while ((byteRead = in.read(buffer, 0, 8192)) != -1) {
  900. os.write(buffer, 0, byteRead);
  901. }
  902. os.flush();
  903. os.close();
  904. in.close();
  905. }
  906. catch (IOException e) {
  907. try {
  908. os.flush();
  909. os.close();
  910. }
  911. catch (IOException e1) {
  912. }
  913. throw new CommonException("bizarea.AnnualService.downLoadFile");
  914. }
  915. }
  916. public static String getDisFileName(String bakstr) {
  917. Calendar ca = Calendar.getInstance();
  918. ca.setTime(new java.util.Date());
  919. SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddkkmmssSSS");
  920. String date = simple.format(ca.getTime());
  921. String randomstr = String.valueOf(Math.random());
  922. String wantstr = randomstr.substring(randomstr.length() - 6, randomstr.length());
  923. return date + wantstr + bakstr;
  924. }
  925. public static String getFrontStr(String filename) {
  926. return filename.substring(0, filename.length() - 4);
  927. }
  928. public static void saveFile(InputStream is, String filePath, String fileName) {
  929. saveFile(is, filePath, fileName, false);
  930. }
  931. }