1
0

FileUtil.java 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package com.kmall.common.utils.excel;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.io.*;
  4. import java.util.zip.ZipInputStream;
  5. /**
  6. * FileUtil. Simple file operation class.
  7. *
  8. * @author BeanSoft
  9. */
  10. public class FileUtil {
  11. /**
  12. * The buffer.
  13. */
  14. protected static byte buf[] = new byte[1024];
  15. /**
  16. * 创建路径
  17. *
  18. * @param path
  19. * @return
  20. */
  21. public static boolean mkdirs(String path) {
  22. try {
  23. File f = new File(path);
  24. if (!f.exists()) {
  25. f.mkdirs();
  26. }
  27. } catch (Exception e) {
  28. return false;
  29. }
  30. return true;
  31. }
  32. /**
  33. * Read content from local file. FIXME How to judge UTF-8 and GBK, the correct code should be: FileReader fr = new FileReader(new
  34. * InputStreamReader(fileName, "ENCODING")); Might let the user select the encoding would be a better idea. While reading UTF-8 files, the content
  35. * is bad when saved out.
  36. *
  37. * @param fileName
  38. * - local file name to read
  39. * @return
  40. * @throws Exception
  41. */
  42. public static String readFileAsString(String fileName) throws Exception {
  43. String content = new String(readFileBinary(fileName));
  44. return content;
  45. }
  46. /**
  47. * 读取文件并返回为给定字符集的字符串.
  48. *
  49. * @param fileName
  50. * @param encoding
  51. * @return
  52. * @throws Exception
  53. */
  54. public static String readFileAsString(String fileName, String encoding) throws Exception {
  55. String content = new String(readFileBinary(fileName), encoding);
  56. return content;
  57. }
  58. /**
  59. * 读取文件并返回为给定字符集的字符串.
  60. *
  61. * @return
  62. * @throws IOException
  63. * @throws Exception
  64. */
  65. public static String readFileAsString(InputStream in) throws IOException {
  66. String content = new String(readFileBinary(in));
  67. return content;
  68. }
  69. /**
  70. * Read content from local file to binary byte array.
  71. *
  72. * @param fileName
  73. * - local file name to read
  74. * @return
  75. * @throws Exception
  76. */
  77. public static byte[] readFileBinary(String fileName) throws Exception {
  78. FileInputStream fin = new FileInputStream(fileName);
  79. return readFileBinary(fin);
  80. }
  81. /**
  82. * 从输入流读取数据为二进制字节数组.
  83. *
  84. * @param streamIn
  85. * @return
  86. * @throws IOException
  87. */
  88. public static byte[] readFileBinary(InputStream streamIn) throws IOException {
  89. BufferedInputStream in = new BufferedInputStream(streamIn);
  90. ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
  91. int len;
  92. while ((len = in.read(buf)) >= 0)
  93. out.write(buf, 0, len);
  94. in.close();
  95. return out.toByteArray();
  96. }
  97. /**
  98. * Write string content to local file.
  99. *
  100. * @param fileName
  101. * - local file name will write to
  102. * @param content
  103. * String text
  104. * @return true if success
  105. * @throws IOException
  106. */
  107. public static boolean writeFileString(String fileName, String content) throws IOException {
  108. FileWriter fout = new FileWriter(fileName);
  109. fout.write(content);
  110. fout.close();
  111. return true;
  112. }
  113. /**
  114. * Write string content to local file using given character encoding.
  115. *
  116. * @param fileName
  117. * - local file name will write to
  118. * @param content
  119. * String text
  120. * @param encoding
  121. * the encoding
  122. * @return true if success
  123. * @throws IOException
  124. */
  125. public static boolean writeFileString(String fileName, String content, String encoding) throws IOException {
  126. OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(fileName), encoding);
  127. fout.write(content);
  128. fout.close();
  129. return true;
  130. }
  131. /**
  132. * Write binary byte array to local file.
  133. *
  134. * @param fileName
  135. * - local file name will write to
  136. * @param content
  137. * binary byte array
  138. * @return true if success
  139. * @throws IOException
  140. */
  141. public static boolean writeFileBinary(String fileName, byte[] content) throws IOException {
  142. if (content == null || StringUtils.isEmpty(fileName)) {
  143. return false;
  144. }
  145. FileOutputStream fout = null;
  146. try {
  147. fout = new FileOutputStream(fileName);
  148. fout.write(content);
  149. } catch (IOException e) {
  150. throw e;
  151. } finally {
  152. if (fout != null) {
  153. try {
  154. fout.close();
  155. } catch (IOException e) {
  156. }
  157. }
  158. }
  159. return true;
  160. }
  161. /**
  162. * 检查文件名是否合法.文件名字不能包含字符\/:*?"<>|
  163. *
  164. * ,不包含路径
  165. * @return boolean is valid file name
  166. */
  167. public static boolean isValidFileName(String fileName) {
  168. boolean isValid = true;
  169. String errChar = "\\/:*?\"<>|"; //
  170. if (fileName == null || fileName.length() == 0) {
  171. isValid = false;
  172. } else {
  173. for (int i = 0; i < errChar.length(); i++) {
  174. if (fileName.indexOf(errChar.charAt(i)) != -1) {
  175. isValid = false;
  176. break;
  177. }
  178. }
  179. }
  180. return isValid;
  181. }
  182. /**
  183. * 把非法文件名转换为合法文件名.
  184. *
  185. * @param fileName
  186. * @return
  187. */
  188. public static String replaceInvalidFileChars(String fileName) {
  189. StringBuffer out = new StringBuffer();
  190. for (int i = 0; i < fileName.length(); i++) {
  191. char ch = fileName.charAt(i);
  192. // Replace invlid chars: \\/:*?\"<>|
  193. switch (ch) {
  194. case '\\':
  195. case '/':
  196. case ':':
  197. case '*':
  198. case '?':
  199. case '\"':
  200. case '<':
  201. case '>':
  202. case '|':
  203. out.append('_');
  204. break;
  205. default:
  206. out.append(ch);
  207. }
  208. }
  209. return out.toString();
  210. }
  211. /**
  212. * Convert a given file name to a URL(URI) string.
  213. *
  214. * @param fileName
  215. * - the file to parse
  216. * @return - URL string
  217. */
  218. public static String filePathToURL(String fileName) {
  219. String fileUrl = new File(fileName).toURI().toString();
  220. return fileUrl;
  221. }
  222. /**
  223. * Write string content to local file.
  224. *
  225. * @param fileName
  226. * - local file name will write to
  227. * @param content
  228. * String text
  229. * @return true if success
  230. * @throws IOException
  231. */
  232. public static boolean appendFileString(String fileName, String content) throws IOException {
  233. OutputStreamWriter fout = new OutputStreamWriter(new FileOutputStream(fileName, true), "UTF-8");
  234. fout.write(content);
  235. fout.close();
  236. return true;
  237. }
  238. /**
  239. * 根据文件路径和文件名获取文件名
  240. *
  241. * @param filePathAndName
  242. * @return
  243. */
  244. public static String getFileName(String filePathAndName) {
  245. int a = filePathAndName.lastIndexOf("\\");
  246. int b = filePathAndName.lastIndexOf("/");
  247. String fileName = filePathAndName.substring((a > b ? a : b) + 1, filePathAndName.length());
  248. return fileName;
  249. }
  250. public static boolean copy(String fileFrom, String fileTo) {
  251. FileInputStream in = null;
  252. FileOutputStream out = null;
  253. try {
  254. in = new FileInputStream(fileFrom);
  255. out = new FileOutputStream(fileTo);
  256. byte[] bt = new byte[1024];
  257. int count;
  258. while ((count = in.read(bt)) > 0) {
  259. out.write(bt, 0, count);
  260. }
  261. return true;
  262. } catch (IOException ex) {
  263. ex.printStackTrace();
  264. return false;
  265. } finally {
  266. try {
  267. if (in != null) {
  268. in.close();
  269. }
  270. } catch (IOException e) {
  271. e.printStackTrace();
  272. }
  273. try {
  274. if (out != null) {
  275. out.close();
  276. }
  277. } catch (IOException e) {
  278. e.printStackTrace();
  279. }
  280. }
  281. }
  282. /**
  283. * 读取输入流
  284. * @param inStream
  285. * @return
  286. * @throws Exception
  287. */
  288. public static byte[] readInputStream(InputStream inStream) throws Exception {
  289. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  290. //创建一个Buffer字符串
  291. byte[] buffer = new byte[1024];
  292. //每次读取的字符串长度,如果为-1,代表全部读取完毕
  293. int len = 0;
  294. //读取一定数量的字节从输入流并存入缓冲区 buffer
  295. while ((len = inStream.read(buffer)) != -1) {
  296. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
  297. //写 len字节指定字节数组中的偏移 off开始到输出流。
  298. outStream.write(buffer, 0, len);
  299. }
  300. //关闭输入流
  301. inStream.close();
  302. //把outStream里的数据写入内存
  303. return outStream.toByteArray();
  304. }
  305. /**
  306. * 读取输入流
  307. * @param inStream
  308. * @return
  309. * @throws Exception
  310. */
  311. public static byte[] readZipInputStream(ZipInputStream inStream) throws Exception {
  312. ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  313. //创建一个Buffer字符串
  314. byte[] buffer = new byte[1024];
  315. //每次读取的字符串长度,如果为-1,代表全部读取完毕
  316. int len = 0;
  317. //读取一定数量的字节从输入流并存入缓冲区 buffer
  318. while ((len = inStream.read(buffer)) != -1) {
  319. //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
  320. //写 len字节指定字节数组中的偏移 off开始到输出流。
  321. outStream.write(buffer, 0, len);
  322. }
  323. //关闭当前的压缩条目并将流用于读取下一个条目。
  324. inStream.closeEntry();
  325. //把outStream里的数据写入内存
  326. return outStream.toByteArray();
  327. }
  328. //删除指定文件夹下所有文件
  329. //param path 文件夹完整绝对路径
  330. public static boolean delAllFile(String path) {
  331. boolean flag = false;
  332. File file = new File(path);
  333. if (!file.exists()) {
  334. return flag;
  335. }
  336. if (!file.isDirectory()) {
  337. return flag;
  338. }
  339. String[] tempList = file.list();
  340. File temp = null;
  341. for (int i = 0; i < tempList.length; i++) {
  342. if (path.endsWith(File.separator)) {
  343. temp = new File(path + tempList[i]);
  344. } else {
  345. temp = new File(path + File.separator + tempList[i]);
  346. }
  347. if (temp.isFile()) {
  348. temp.delete();
  349. }
  350. if (temp.isDirectory()) {
  351. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
  352. delFolder(path + "/" + tempList[i]);//再删除空文件夹
  353. flag = true;
  354. }
  355. }
  356. return flag;
  357. }
  358. public static void delFolder(String folderPath) {
  359. try {
  360. delAllFile(folderPath); //删除完里面所有内容
  361. String filePath = folderPath;
  362. filePath = filePath.toString();
  363. File myFilePath = new File(filePath);
  364. myFilePath.delete(); //删除空文件夹
  365. } catch (Exception e) {
  366. e.printStackTrace();
  367. }
  368. }
  369. }