FileUtil.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package com.persagy.framework.util;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.FileReader;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.io.InputStreamReader;
  11. import java.io.LineNumberReader;
  12. import java.io.OutputStream;
  13. import java.io.OutputStreamWriter;
  14. import java.nio.channels.FileChannel;
  15. import java.nio.file.Files;
  16. import java.util.ArrayList;
  17. import java.util.List;
  18. /**
  19. * Description: 文件操作工具类
  20. * Company: Persagy
  21. * @author cuixubin
  22. * @version 1.0
  23. * @since: 2018年7月11日: 下午4:56:38
  24. * Update By cuixubin 2018年7月11日: 下午4:56:38
  25. */
  26. public class FileUtil {
  27. public static void main(String[] args) throws Exception {
  28. System.out.println(createFile("d:/test1.json"));
  29. }
  30. /**
  31. * Description: 将字节数组写入到文件
  32. * @param fileName 文件名.后缀名
  33. * @param data 数据
  34. * @return
  35. * @throws Exception File
  36. * @author cuixubin
  37. * @since 2018年9月25日: 上午10:35:41
  38. * Update By cuixubin 2018年9月25日: 上午10:35:41
  39. */
  40. public static File writeByteToFile(String fileName, byte[] data) throws Exception {
  41. String basePath = CommonToolUtils.getFileStorageDictionary();
  42. basePath += File.separator + "imageServiceSource" + File.separator + fileName;
  43. File file = createAndGetFile(basePath);
  44. return writeByteToFile(file, data);
  45. }
  46. /**
  47. * Description: 将字节数据写入到文件
  48. * @param file 目标文件
  49. * @param data 数据
  50. * @return
  51. * @throws Exception File
  52. * @author cuixubin
  53. * @since 2018年9月25日: 上午10:32:57
  54. * Update By cuixubin 2018年9月25日: 上午10:32:57
  55. */
  56. public static File writeByteToFile(File file, byte[] data) throws Exception {
  57. if(null == file || !file.exists() || file.isDirectory() || data == null) {
  58. return null;
  59. }
  60. try(FileOutputStream out = new FileOutputStream(file)) {
  61. out.write(data);
  62. }
  63. return file;
  64. }
  65. /**
  66. * Description: 删除目录下的文件及子目录
  67. * @param path 目录的绝对路径
  68. * @param delFailedFiles 删除失败的文件或文件夹路径信息集合
  69. * @return List<String>
  70. * @author cuixubin
  71. * @since 2018年7月11日: 下午5:20:53
  72. * Update By cuixubin 2018年7月11日: 下午5:20:53
  73. */
  74. public static List<String> delDirectory(String path, List<String> delFailedFiles) {
  75. if(null == delFailedFiles) {
  76. delFailedFiles = new ArrayList<>();
  77. }
  78. if(null == path) {
  79. return delFailedFiles;
  80. }
  81. File file = new File(path);
  82. if(file.exists()) {
  83. if(file.isFile()) {
  84. file.delete();
  85. }
  86. if(file.isDirectory()) {
  87. String[] files = file.list();
  88. for(String fpath : files) {
  89. path = path.endsWith(File.separator) ? path : path + File.separator;
  90. fpath = path + fpath;
  91. delDirectory(fpath, delFailedFiles);
  92. }
  93. file.delete();
  94. }
  95. delFailedFiles.add(path);
  96. }
  97. return delFailedFiles;
  98. }
  99. /**
  100. * Description: 读取文件夹下的文件
  101. * @param filepath 文件夹绝对路径
  102. * @param fileList 存放文件的集合
  103. * @return List<File>
  104. */
  105. public static void getFilesInDir(String filepath, List<File> fileList){
  106. fileList = fileList == null ? new ArrayList<>() : fileList;
  107. File file = new File(filepath);
  108. if (!file.isDirectory()) {
  109. // 是文件
  110. fileList.add(file);
  111. } else if (file.isDirectory()) {
  112. // 是文件夹
  113. String[] filelist = file.list();
  114. for (int i = 0; i < filelist.length; i++) {
  115. File readfile = new File(filepath + File.separator + filelist[i]);
  116. if (!readfile.isDirectory()) {
  117. fileList.add(readfile);
  118. } else if (readfile.isDirectory()) {
  119. getFilesInDir(filepath + File.separator + filelist[i], fileList);
  120. }
  121. }
  122. }
  123. }
  124. /**
  125. * Description: 根据文件路径创建文件(如果文件所在文件夹不存在则自动创建),如果所要创建的文件已存在则不创建
  126. * @param filePath 路径+文件名+后缀
  127. * @return boolean true-创建成功或文件已存在;false-创建失败
  128. */
  129. public static boolean createFile(String filePath) {
  130. boolean createOK = false;
  131. if(null != filePath) {
  132. if(filePath.lastIndexOf(File.separator) > 0) {
  133. String dirPath = filePath.substring(0, filePath.lastIndexOf(File.separator));
  134. if (dirPath != null && !dirPath.endsWith(":")) {
  135. createDir(dirPath);
  136. }
  137. }
  138. File file = new File(filePath);
  139. if(!file.exists()) {
  140. try {
  141. return file.createNewFile();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. }
  145. } else {
  146. createOK = true;
  147. }
  148. }
  149. return createOK;
  150. }
  151. /**
  152. * Description: 根据文件路径创建文件(如果文件所在文件夹不存在则自动创建),如果所要创建的文件已存在则不创建
  153. * @param filePath 路径+文件名+后缀
  154. * @return File 创建成功返回文件对象,否则返回null
  155. */
  156. public static File createAndGetFile(String filePath) {
  157. if(createFile(filePath)) {
  158. return new File(filePath);
  159. }
  160. return null;
  161. }
  162. /**
  163. * Description: 根据文件目录和文件名创建文件
  164. * @param dirPath 文件目录路径
  165. * @param fileName 文件名+后缀
  166. * @return boolean
  167. */
  168. public static boolean createFile(String dirPath, String fileName) {
  169. boolean createOK = false;
  170. if(createDir(dirPath)) {
  171. dirPath = dirPath.endsWith(File.separator) ? dirPath : dirPath + File.separator;
  172. return createFile(dirPath + fileName);
  173. }
  174. return createOK;
  175. }
  176. /**
  177. * Description: 创建文件夹
  178. * @param dirPath 文件夹路径
  179. * @return boolean true-创建成功;false-创建失败
  180. */
  181. public static boolean createDir(String dirPath) {
  182. boolean createOK = false;
  183. if(null != dirPath) {
  184. File file = new File(dirPath);
  185. if(!file.exists()) {
  186. return file.mkdirs();
  187. } else {
  188. createOK = true;
  189. }
  190. }
  191. return createOK;
  192. }
  193. /**
  194. * Description: 删除文件
  195. * @param file
  196. * @return boolean
  197. */
  198. public static boolean delFile(File file) {
  199. if(null != file && file.exists() && file.isFile()) {
  200. return file.delete();
  201. }
  202. return false;
  203. }
  204. /**
  205. * Description: 删除文件
  206. * @param filePath 文件绝对路径
  207. * @return boolean true-文件存在且删除成功;false-删除失败
  208. */
  209. public static boolean delFile(String filePath) {
  210. if(null != filePath) {
  211. File file = new File(filePath);
  212. return delFile(file);
  213. }
  214. return false;
  215. }
  216. /**
  217. *
  218. * Description: 删除文件夹,及文件夹下的所有子文件夹和文件
  219. * @param folderPath void
  220. */
  221. public static boolean delFolder(String folderPath) {
  222. // 删除完里面所有内容
  223. if(!delAllFile(folderPath)) {
  224. return false;
  225. }
  226. try {
  227. String filePath = folderPath.toString();
  228. File myFilePath = new File(filePath);
  229. // 删除空文件夹
  230. if(null != myFilePath && myFilePath.exists()) {
  231. return myFilePath.delete();
  232. }
  233. } catch (Exception e) {
  234. e.printStackTrace();
  235. }
  236. return false;
  237. }
  238. /**
  239. * Description: 删除目录下的所有文件和文件夹
  240. * @param path 目录绝对路径
  241. * @return boolean true-删除成功;false-删除失败
  242. */
  243. public static boolean delAllFile(String path) {
  244. boolean flag = true;
  245. File file = new File(path);
  246. if (!file.exists()) {
  247. return false;
  248. }
  249. if (!file.isDirectory()) {
  250. return false;
  251. }
  252. String[] tempList = file.list();
  253. File temp = null;
  254. for (int i = 0; i < tempList.length; i++) {
  255. if (path.endsWith(File.separator)) {
  256. temp = new File(path + tempList[i]);
  257. } else {
  258. temp = new File(path + File.separator + tempList[i]);
  259. }
  260. if (temp.isFile()) {
  261. temp.delete();
  262. }
  263. if (temp.isDirectory()) {
  264. // 先删除文件夹里面的文件
  265. delAllFile(path + File.separator + tempList[i]);
  266. // 再删除空文件夹
  267. delFolder(path + File.separator + tempList[i]);
  268. }
  269. }
  270. return flag;
  271. }
  272. /**
  273. * 使用流拷贝文件,速度慢
  274. * @param source 源文件
  275. * @param dest 目标文件
  276. * @throws IOException
  277. */
  278. public static void copyFile1(File source, File dest) throws IOException {
  279. InputStream input = null;
  280. OutputStream output = null;
  281. try {
  282. input = new FileInputStream(source);
  283. output = new FileOutputStream(dest);
  284. byte[] buf = new byte[1024];
  285. int bytesRead;
  286. while ((bytesRead = input.read(buf)) > 0) {
  287. output.write(buf, 0, bytesRead);
  288. }
  289. } finally {
  290. input.close();
  291. output.close();
  292. }
  293. }
  294. /**
  295. * 使用FileChannel拷贝文件,速度快
  296. * @param source 源文件
  297. * @param dest 目标文件
  298. * @throws IOException
  299. */
  300. public static void copyFile2(File source, File dest) throws IOException {
  301. try (FileChannel inputChannel = new FileInputStream(source).getChannel();
  302. FileChannel outputChannel = new FileOutputStream(dest).getChannel();) {
  303. outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
  304. }catch (Exception e) {
  305. e.printStackTrace();
  306. }
  307. }
  308. /**
  309. * 使用Java7的Files类复制文件
  310. * @param source 源文件
  311. * @param dest 目标文件
  312. * @throws IOException
  313. */
  314. public static void copyFile3(File source, File dest) throws IOException {
  315. Files.copy(source.toPath(), dest.toPath());
  316. }
  317. /**
  318. * Description: 获取文件中内容的总行数
  319. * @param file
  320. * @return Integer 文件中内容总行数,默认0行
  321. */
  322. public static Integer getLineNumber(File file) {
  323. Integer lineNumber = 0;
  324. if(file != null && file.exists() && file.isFile()) {
  325. try(LineNumberReader lnr = new LineNumberReader(new FileReader(file));) {
  326. lnr.skip(Long.MAX_VALUE);
  327. lineNumber = lnr.getLineNumber() + 1;
  328. }catch (Exception e) {
  329. e.printStackTrace();
  330. }
  331. }
  332. return lineNumber;
  333. }
  334. /**
  335. * Description: 按行读取文件中的信息存入到List集合中
  336. * @param file
  337. * @return List<String> 文件中的内容,按行存入集合,默认返回空集合
  338. */
  339. public static List<String> readFileToList(File file) {
  340. List<String> contentList = new ArrayList<>();
  341. if(null == file || !file.exists() || !file.isFile()) {
  342. return contentList;
  343. }
  344. try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
  345. BufferedReader br = new BufferedReader(isr);) {
  346. String temp = null;
  347. while ((temp = br.readLine()) != null) {
  348. contentList.add(temp);
  349. }
  350. } catch (Exception e) {
  351. e.printStackTrace();
  352. }
  353. return contentList;
  354. }
  355. /**
  356. * Description: 按行读取文件中的信息,将所读到信息写入到一个字符串当中
  357. * @param file 文件
  358. * @return String 文件中的信息
  359. * @author cuixubin
  360. * @since 2018年7月11日: 下午5:26:35
  361. * Update By cuixubin 2018年7月11日: 下午5:26:35
  362. */
  363. public static String readFileToString(File file) {
  364. StringBuffer sbStr = new StringBuffer();
  365. List<String> dataStringList = readFileToList(file);
  366. if(null != dataStringList) {
  367. for(String str : dataStringList) {
  368. sbStr.append(str);
  369. }
  370. }
  371. return sbStr.toString();
  372. }
  373. /**
  374. * Description: 将字符串写入到指定文件
  375. * @param file 已存在的文件绝对路径
  376. * @param str 要写入的字符串
  377. * @param append true-在文件中追加字符串;false先清空文件中原有内容再写入字符串
  378. * @throws Exception void
  379. * @author cuixubin
  380. * @since 2018年8月19日: 下午8:01:41
  381. * Update By cuixubin 2018年8月19日: 下午8:01:41
  382. */
  383. public static void writeInFile(File file, String str, boolean append) throws Exception{
  384. if(null == file || !file.exists() || !file.isFile()) {
  385. throw new Exception("文件不存在!");
  386. }
  387. if(str == null) {
  388. return;
  389. }
  390. /*
  391. try(PrintStream ps = new PrintStream(new FileOutputStream(file));){
  392. if(append) {
  393. ps.append(str);
  394. }else {
  395. ps.println(str);
  396. }
  397. }
  398. */
  399. BufferedWriter out = null;
  400. try {
  401. out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append)));
  402. out.write(str + "\r\n");
  403. } catch (Exception e) {
  404. e.printStackTrace();
  405. } finally {
  406. try {
  407. out.close();
  408. } catch (IOException e) {
  409. e.printStackTrace();
  410. }
  411. }
  412. }
  413. }