FileUtil.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. package api.common.util;
  2. import lombok.SneakyThrows;
  3. import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
  4. import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
  5. import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
  6. import org.springframework.util.ResourceUtils;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.io.*;
  9. import java.nio.MappedByteBuffer;
  10. import java.nio.channels.FileChannel;
  11. import java.nio.charset.StandardCharsets;
  12. import java.nio.file.Files;
  13. import java.nio.file.Paths;
  14. import java.util.*;
  15. public class FileUtil {
  16. /**
  17. * 获取所有同一类型的文件列表。
  18. *
  19. * @param rootPath 文件 File 路径。
  20. * @param suffix 文件后缀类型。
  21. */
  22. @SneakyThrows
  23. public static List<String> listAbsolutePathByFiletype(String rootPath, String suffix) {
  24. List<String> result = new LinkedList<>();
  25. File rootFile = new File(rootPath);
  26. //1 判断文件是否存在
  27. if (!rootFile.exists()) {
  28. throw new RuntimeException("FileUtil--listAbsolutePathByFiletype 文件 " + rootPath + " 不存在!");
  29. }
  30. //2 判断是否是文件
  31. if (rootFile.isFile() && rootFile.getName().equals(suffix)) {
  32. return new ArrayList<>(Collections.singletonList(rootPath));
  33. }
  34. //3 判断是否是目录
  35. if (rootFile.isDirectory()) {
  36. File[] children = rootFile.listFiles();
  37. if (children != null) {
  38. for (File child : children) {
  39. result.addAll(listAbsolutePathByFiletype(child.getAbsolutePath(), suffix));
  40. }
  41. }
  42. }
  43. return result;
  44. }
  45. /**
  46. * 获取当前目录下的一级文件全路径列表
  47. * @param path 根路径
  48. * @return 文件全路径列表
  49. */
  50. public static List<String> ls(String path) {
  51. File[] files = new File(path).listFiles();
  52. if (files == null){
  53. throw new RuntimeException("路径不存在!");
  54. }
  55. List<String> result = new ArrayList<>();
  56. for (File file : files) {
  57. result.add(file.getAbsolutePath()) ;
  58. }
  59. return result;
  60. }
  61. @SneakyThrows
  62. public static String read(String path){
  63. return read(getFile(path));
  64. }
  65. public static String cat(String path) throws Exception {
  66. return read(getFile(path));
  67. }
  68. public static String read(File file) throws IOException {
  69. return read(new FileInputStream(file));
  70. }
  71. public static String read(InputStream inputStream) throws IOException {
  72. StringBuilder result = new StringBuilder();
  73. byte[] buf = new byte[4096];//创建字节数组,存储临时读取的数据
  74. int len;//记录数据读取的长度
  75. //循环读取数据
  76. while ((len = inputStream.read(buf)) != -1) { //长度为-1则读取完毕
  77. result.append(new String(buf, 0, len)).append("\n");
  78. }
  79. inputStream.close();
  80. return result.toString();
  81. }
  82. // -------------------------------- A --------------------------------
  83. /**
  84. * 添加文件后缀
  85. *
  86. * @param url 路径
  87. * @return 有后缀名的文件
  88. */
  89. public static String addSeparator(String url) {
  90. if (File.separator.equals(url.charAt(url.length() - 1) + "")) {
  91. return url;
  92. }
  93. return url + File.separator;
  94. }
  95. /**
  96. * 添加文件后缀
  97. *
  98. * @param ambiguousFileName 不确定是否有后缀的文件名
  99. * @return 有后缀名的文件
  100. */
  101. public static String addSuffix(String ambiguousFileName, String suffix) {
  102. if (ambiguousFileName == null || "".equals(ambiguousFileName)) {
  103. throw new RuntimeException("文件名参数为空!");
  104. }
  105. String[] split = ambiguousFileName.split("\\.");
  106. return split[0] + suffix;
  107. }
  108. // -------------------------------- B --------------------------------
  109. // -------------------------------- C --------------------------------
  110. /**
  111. * 检查文件
  112. * 0 代表不存在
  113. * 1 代表是文件
  114. * 2 代表是目录
  115. *
  116. * @param file 文件
  117. * @return 是否正确
  118. */
  119. public static String checkFile(File file) {
  120. if (!file.exists()) {
  121. return "0";
  122. }
  123. if (file.isFile()) {
  124. return "1";
  125. }
  126. if (file.isDirectory()) {
  127. return "2";
  128. }
  129. return null;
  130. }
  131. /**
  132. * 检查文件后缀
  133. *
  134. * @param file 文件
  135. * @param suffix 文件后缀
  136. * @return 是否正确
  137. */
  138. public static boolean checkFileType(File file, String suffix) {
  139. String fileName = file.getName();
  140. int fileNameLength = fileName.length();
  141. int suffixLength = suffix.length();
  142. if (fileNameLength < suffixLength) {
  143. return false;
  144. }
  145. return suffix.equals(fileName.substring(fileNameLength - suffixLength));
  146. }
  147. /**
  148. * 自适应转换文件大小的单位
  149. *
  150. * @param dataSize long 型的文件大小
  151. * @return 带单位的 String 类型文件大小
  152. */
  153. public static String convertUnit(long dataSize) {
  154. String dataSizeStr = null;
  155. if (dataSize >= 0 && dataSize < 1024) {
  156. dataSizeStr = dataSize + "B";
  157. } else if (dataSize >= 1024 && dataSize < 1024 * 1024) {
  158. dataSizeStr = dataSize / 1024 + "KB";
  159. } else if (dataSize >= 1024 * 1024 && dataSize < 1024 * 1024 * 1024) {
  160. dataSizeStr = dataSize / 1024 / 1024 + "MB";
  161. } else if (dataSize >= 1024 * 1024 * 1024 && dataSize < 1024 * 1024 * 1024 * 1024L) {
  162. dataSizeStr = dataSize / 1024 / 1024 / 1024 + "GB";
  163. } else if (dataSize >= 1024 * 1024 * 1024 * 1024L) {
  164. dataSizeStr = dataSize / 1024 / 1024 / 1024 / 1024 + "TB";
  165. }
  166. return dataSizeStr;
  167. }
  168. /**
  169. * 计算目录包含的文件数量
  170. *
  171. * @param directory 目录的 File 对象
  172. * @return 文件数量
  173. */
  174. public static int count(File directory) {
  175. return Objects.requireNonNull(directory.listFiles()).length;
  176. }
  177. /**
  178. * 计算目录包含的文件数量
  179. *
  180. * @param directoryPath 目录的路径
  181. * @return 文件数量
  182. */
  183. public static int count(String directoryPath) throws Exception {
  184. return count(getDirectory(directoryPath));
  185. }
  186. /**
  187. * 复制文件
  188. *
  189. * @param source 原始文件路径
  190. * @param target 目标路径
  191. * @throws Exception 异常
  192. */
  193. public static void copy(String source, String target) throws Exception {
  194. File targetFile = new File(target);
  195. boolean delete = true;
  196. if (targetFile.exists()) {
  197. delete = targetFile.delete();
  198. }
  199. if (delete) {
  200. createParentDirectory(target);
  201. Files.copy(getFile(source).toPath(), new File(target).toPath());
  202. } else {
  203. throw new Exception("删除 " + target + " 失败!");
  204. }
  205. }
  206. /**
  207. * 创建目录
  208. */
  209. public static boolean createDirectory(String path) {
  210. boolean mkdir = false;
  211. File file = new File(path);
  212. if (!file.exists()) {
  213. mkdir = file.mkdirs();
  214. }
  215. return mkdir;
  216. }
  217. /**
  218. * 创建父目录
  219. */
  220. public static boolean createParentDirectory(String path) {
  221. boolean mkdir = false;
  222. File file = new File(path);
  223. if (!file.getParentFile().exists()) {
  224. mkdir = file.getParentFile().mkdirs();
  225. }
  226. return mkdir;
  227. }
  228. /**
  229. * 创建父目录
  230. */
  231. public static boolean createParentDirectory(File file) {
  232. boolean mkdir = true;
  233. if (!file.getParentFile().exists()) {
  234. mkdir = file.getParentFile().mkdirs();
  235. }
  236. return mkdir;
  237. }
  238. /**
  239. * 创建文件。
  240. */
  241. public static boolean createFile(String path) throws IOException {
  242. File file = new File(path);
  243. boolean result = createParentDirectory(file);
  244. if (!file.exists()) {
  245. result = file.createNewFile();
  246. }
  247. return result;
  248. }
  249. /**
  250. * 创建文件。
  251. */
  252. public static boolean createFile(File file) throws IOException {
  253. boolean result = createParentDirectory(file);
  254. if (!file.exists()) {
  255. result = file.createNewFile();
  256. }
  257. return result;
  258. }
  259. /**
  260. * 拷贝文件。
  261. */
  262. public static void copyFile(String readFrom, String writeTo) throws IOException {
  263. createParentDirectory(writeTo);
  264. FileInputStream fileInputStream = new FileInputStream(readFrom);
  265. FileOutputStream fileOutputStream = new FileOutputStream(writeTo);
  266. FileChannel readChannel = fileInputStream.getChannel();
  267. FileChannel writeChannel = fileOutputStream.getChannel();
  268. //自动生成与文件大小相同但不超过 8096 的缓存,即缓存最大为 8096。
  269. writeChannel.transferFrom(readChannel, 0, readChannel.size());
  270. writeChannel.close();
  271. readChannel.close();
  272. fileOutputStream.close();
  273. fileInputStream.close();
  274. }
  275. public static void copyBytes(InputStream in, OutputStream out, int bufferSize) throws IOException {
  276. byte[] buffer = new byte[bufferSize];
  277. for (int bytesRead = in.read(buffer); bytesRead >= 0; bytesRead = in.read(buffer)) {
  278. out.write(buffer, 0, bytesRead);
  279. }
  280. }
  281. // -------------------------------- D --------------------------------
  282. /**
  283. * 供 http 下载使用
  284. *
  285. * @param fileName 文件名
  286. * @param in 输入流
  287. * @param response 响应对象
  288. * @param bufferSize 缓存大小
  289. * @throws IOException 异常
  290. */
  291. public static void downloadForHttp(String fileName, InputStream in, HttpServletResponse response, int bufferSize) throws IOException {
  292. response.setContentType("application/octet-stream;charset=utf-8");
  293. response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
  294. copyBytes(in, response.getOutputStream(), bufferSize);
  295. }
  296. public static Set<String> decompress(InputStream inputStream, String targetDirectoryPath, String fileType) throws IOException {
  297. Set<String> fileList = new HashSet<>();
  298. if (!targetDirectoryPath.endsWith("/")) {
  299. targetDirectoryPath += "/";
  300. }
  301. if (".tar".equals(fileType)) {
  302. TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
  303. TarArchiveEntry entry;
  304. // 将 tar 文件解压到 extractPath 目录下
  305. while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
  306. if (entry.isDirectory()) {
  307. continue;
  308. }
  309. createDirectory(targetDirectoryPath);
  310. File currentFile = new File(targetDirectoryPath + entry.getName());
  311. File parent = currentFile.getParentFile();
  312. if (!parent.exists()) {
  313. boolean mkdirs = parent.mkdirs();
  314. }
  315. fileList.add(currentFile.getAbsolutePath());
  316. // 将文件写出到解压的目录
  317. copyBytes(tarArchiveInputStream, new FileOutputStream(currentFile), 4096);
  318. }
  319. }
  320. if (".tar.gz".equals(fileType)|| ".tgz".equals(fileType)|| ".gz".equals(fileType)) {
  321. TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream((new GzipCompressorInputStream(inputStream)));
  322. TarArchiveEntry entry;
  323. // 将 tar 文件解压到 extractPath 目录下
  324. while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
  325. if (entry.isDirectory()) {
  326. continue;
  327. }
  328. createDirectory(targetDirectoryPath);
  329. File currentFile = new File(targetDirectoryPath + entry.getName());
  330. File parent = currentFile.getParentFile();
  331. if (!parent.exists()) {
  332. boolean mkdirs = parent.mkdirs();
  333. }
  334. fileList.add(currentFile.getAbsolutePath());
  335. // 将文件写出到解压的目录
  336. copyBytes(tarArchiveInputStream, new FileOutputStream(currentFile), 4096);
  337. }
  338. }
  339. inputStream.close();
  340. return fileList;
  341. }
  342. /**
  343. * 扫描压缩包中是否存在指定文件
  344. * @param inputStream
  345. * @param fileType
  346. * @return
  347. * @throws IOException
  348. */
  349. public static boolean scan(InputStream inputStream, String fileType, String targetFileName) throws IOException {
  350. if (".tar".equals(fileType)) {
  351. TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
  352. TarArchiveEntry entry;
  353. // 将 tar 文件解压到 extractPath 目录下
  354. while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
  355. if (entry.getName().contains(targetFileName)){
  356. return true;
  357. }
  358. }
  359. }
  360. if (".tar.gz".equals(fileType)|| ".tgz".equals(fileType)|| ".gz".equals(fileType)) {
  361. TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream((new GzipCompressorInputStream(inputStream)));
  362. TarArchiveEntry entry;
  363. // 将 tar 文件解压到 extractPath 目录下
  364. while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
  365. if (entry.getName().contains(targetFileName)){
  366. return true;
  367. }
  368. }
  369. }
  370. inputStream.close();
  371. return false;
  372. }
  373. // -------------------------------- F --------------------------------
  374. // -------------------------------- G --------------------------------
  375. /**
  376. * 获得去除文件后缀的文件名
  377. */
  378. public static List<String> getAbsolutePathList(File[] files) {
  379. List<String> absolutePathList = new ArrayList<>();
  380. for (File file : files) {
  381. absolutePathList.add(file.getAbsolutePath());
  382. }
  383. return absolutePathList;
  384. }
  385. /**
  386. * 获得目录的 File 对象
  387. */
  388. public static File getDirectory(String path) throws Exception {
  389. // 获取文件
  390. File file = new File(path);
  391. if (!file.exists()) {
  392. throw new Exception("文件" + path + "不存在!");
  393. }
  394. if (!file.isDirectory()) {
  395. throw new Exception("文件" + path + "不是目录!");
  396. }
  397. return file;
  398. }
  399. /**
  400. * 获得去除文件后缀的文件名
  401. */
  402. public static File getFile(String path) throws Exception {
  403. // 获取文件
  404. File file = new File(path);
  405. if (!file.exists()) {
  406. throw new Exception("文件" + path + "不存在!");
  407. }
  408. return file;
  409. }
  410. /**
  411. * 获得去除文件后缀的文件名
  412. */
  413. public static String getFilename(File file) {
  414. return file.getName().split("\\.")[0];
  415. }
  416. /**
  417. * 获得去除文件后缀的文件名
  418. */
  419. public static String getFilename(String path) throws Exception {
  420. return getFilename(getFile(path));
  421. }
  422. /**
  423. * 获得去除文件后缀的文件名
  424. */
  425. public static List<String> getFilenameList(File[] files) {
  426. List<String> fileNameList = new ArrayList<>();
  427. for (File file : files) {
  428. fileNameList.add(file.getName());
  429. }
  430. return fileNameList;
  431. }
  432. /**
  433. * 获取文件行数
  434. *
  435. * @param path 文件路径
  436. * @return 文件行数
  437. * @throws IOException 异常
  438. */
  439. public static long getFileLineNum(String path) throws IOException {
  440. return Files.lines(Paths.get(path)).count();
  441. }
  442. /**
  443. * 获取文件名称
  444. *
  445. * @param path 文件路径
  446. * @return 文件名
  447. */
  448. public static String getFileName(String path) {
  449. return new File(path).getName();
  450. }
  451. /**
  452. * 获取 classpath 文件
  453. *
  454. * @param relativePath 相对路径
  455. */
  456. public static File getResourceFile(String relativePath) throws IOException {
  457. return ResourceUtils.getFile("classpath:" + relativePath);
  458. }
  459. /**
  460. * 获取所有文件列表。
  461. *
  462. * @param root 文件 File 对象。
  463. */
  464. public static List<File> list(File root) throws Exception {
  465. List<File> result = new LinkedList<>();
  466. //1 判断文件是否存在
  467. if (!root.exists()) {
  468. throw new Exception("文件" + root.getAbsolutePath() + "不存在!");
  469. }
  470. //2 判断是否是文件
  471. if (root.isFile()) {
  472. return new ArrayList<>(Collections.singletonList(root));
  473. }
  474. //3 判断是否是目录
  475. if (root.isDirectory()) {
  476. File[] children = root.listFiles();
  477. if (children != null) {
  478. for (File child : children) {
  479. result.addAll(list(child));
  480. }
  481. }
  482. }
  483. return result;
  484. }
  485. /**
  486. * 获取所有文件列表。
  487. *
  488. * @param rootPath 文件 File 对象。
  489. */
  490. public static List<String> list(String rootPath) throws Exception {
  491. List<String> result = new ArrayList<>();
  492. File root = new File(rootPath);
  493. //1 判断文件是否存在
  494. if (!root.exists()) {
  495. throw new Exception("文件" + root.getAbsolutePath() + "不存在!");
  496. }
  497. //2 判断是否是文件
  498. if (root.isFile()) {
  499. return new ArrayList<>(Collections.singletonList(rootPath));
  500. }
  501. //3 判断是否是目录
  502. if (root.isDirectory()) {
  503. File[] children = root.listFiles();
  504. if (children != null) {
  505. for (File child : children) {
  506. result.addAll(list(child.getAbsolutePath()));
  507. }
  508. }
  509. }
  510. return result;
  511. }
  512. /**
  513. * 获取所有同一类型的文件列表。
  514. *
  515. * @param root 文件 File 对象。
  516. * @param suffix 文件后缀类型。
  517. */
  518. public static List<File> listMatchSuffix(File root, String suffix) throws Exception {
  519. List<File> result = new LinkedList<>();
  520. //1 判断文件是否存在
  521. if (!root.exists()) {
  522. throw new Exception("文件" + root.getAbsolutePath() + "不存在!");
  523. }
  524. //2 判断是否是文件
  525. if (root.isFile() && checkFileType(root, suffix)) {
  526. return new ArrayList<>(Collections.singletonList(root));
  527. }
  528. //3 判断是否是目录
  529. if (root.isDirectory()) {
  530. File[] children = root.listFiles();
  531. if (children != null) {
  532. for (File child : children) {
  533. result.addAll(listMatchSuffix(child, suffix));
  534. }
  535. }
  536. }
  537. return result;
  538. }
  539. /**
  540. * 获取所有同一名称的文件列表。
  541. *
  542. * @param root 文件 File 对象。
  543. * @param fullFilename 带后缀的文件名。
  544. */
  545. public static List<File> listMatchName(File root, String fullFilename) throws Exception {
  546. List<File> result = new LinkedList<>();
  547. //1 判断文件是否存在
  548. if (!root.exists()) {
  549. throw new Exception("文件" + root.getAbsolutePath() + "不存在!");
  550. }
  551. //2 判断是否是文件且文件名是否一致
  552. if (root.isFile() && fullFilename.equals(root.getName())) {
  553. return new ArrayList<>(Collections.singletonList(root));
  554. }
  555. //3 判断是否是目录
  556. if (root.isDirectory()) {
  557. File[] children = root.listFiles();
  558. if (children != null) {
  559. for (File child : children) {
  560. result.addAll(listMatchName(child, fullFilename));
  561. }
  562. }
  563. }
  564. return result;
  565. }
  566. /**
  567. * 获得父级文件。
  568. *
  569. * @return 父级文件
  570. */
  571. public static File getParentFile(String path) throws Exception {
  572. return getParentFile(getFile(path));
  573. }
  574. /**
  575. * 获得父级文件。
  576. *
  577. * @return 父级文件
  578. */
  579. public static File getParentFile(File file) {
  580. return file.getParentFile();
  581. }
  582. /**
  583. * 获得父级目录名。
  584. */
  585. public static String getParentDirectoryName(File file) {
  586. return getParentFile(file).getName().split("\\.")[0];
  587. }
  588. /**
  589. * 获得父级目录名。
  590. */
  591. public static String getParentDirectoryName(String path) throws Exception {
  592. return getParentDirectoryName(getFile(path));
  593. }
  594. /**
  595. * 获取路径下的所有文件总大小
  596. */
  597. public static double getSize(File file) throws Exception {
  598. //判断文件是否存在
  599. if (file.exists()) {
  600. //如果是目录则递归计算其内容的总大小
  601. if (file.isDirectory()) {
  602. File[] children = file.listFiles();
  603. if (children == null) {
  604. return 0;
  605. }
  606. double size = 0;
  607. for (File f : children)
  608. size += getSize(f);
  609. return size;
  610. } else {//如果是文件则直接返回其大小,以“兆”为单位
  611. return (double) file.length() / 1024 / 1024;
  612. }
  613. } else {
  614. throw new Exception("文件或者文件夹不存在,请检查路径" + file.getAbsolutePath() + "是否正确!");
  615. }
  616. }
  617. public static String getSuffix(String path) {
  618. String[] split = path.split("\\.");
  619. return split[split.length - 1];
  620. }
  621. /**
  622. * 计算文件大小,递归算法
  623. */
  624. public static long getTotalSizeOfFilesInDir(final File file) throws Exception {
  625. //判断文件是否存在
  626. if (file.exists()) {
  627. if (file.isFile()) {
  628. return file.length();
  629. }
  630. final File[] children = file.listFiles();
  631. long total = 0;
  632. if (children != null) {
  633. for (final File child : children) {
  634. total += getTotalSizeOfFilesInDir(child);
  635. }
  636. }
  637. return total;
  638. } else {
  639. throw new Exception("文件或者文件夹不存在,请检查路径" + file.getAbsolutePath() + "是否正确!");
  640. }
  641. }
  642. // -------------------------------- H --------------------------------
  643. // -------------------------------- I --------------------------------
  644. // -------------------------------- J --------------------------------
  645. // -------------------------------- K --------------------------------
  646. // -------------------------------- L --------------------------------
  647. // -------------------------------- M --------------------------------
  648. /**
  649. * 修改文件。
  650. */
  651. public static void modifyFile(String path, int offset, byte[] bytes) throws IOException {
  652. createFile(path);
  653. RandomAccessFile randomAccessFile = new RandomAccessFile(path, "rw");
  654. FileChannel channel = randomAccessFile.getChannel();
  655. MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, offset, bytes.length);
  656. mappedByteBuffer.put(bytes);
  657. channel.close();
  658. }
  659. /**
  660. * 移动文件或者重命名文件
  661. *
  662. * @param source 原始文件路径
  663. * @param target 目标路径
  664. * @return 是否操作成功
  665. * @throws Exception 异常
  666. */
  667. public static boolean mv(String source, String target) throws Exception {
  668. return getFile(source).renameTo(new File(target));
  669. }
  670. // -------------------------------- N --------------------------------
  671. // -------------------------------- O --------------------------------
  672. // -------------------------------- P --------------------------------
  673. // -------------------------------- Q --------------------------------
  674. // -------------------------------- R --------------------------------
  675. public static String readFile(String path) throws Exception {
  676. return readFile(getFile(path));
  677. }
  678. public static String readFile(File file) throws Exception {
  679. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  680. StringBuilder stringBuilder = new StringBuilder();
  681. String line;
  682. while ((line = reader.readLine()) != null) {
  683. stringBuilder.append(line);
  684. }
  685. reader.close();
  686. return String.valueOf(stringBuilder);
  687. }
  688. public static String readInputStream(InputStream inputStream) throws Exception {
  689. StringBuilder result = new StringBuilder();
  690. byte[] buf = new byte[1024];//创建字节数组,存储临时读取的数据
  691. int len = 0;//记录数据读取的长度
  692. //循环读取数据
  693. while ((len = inputStream.read(buf)) != -1) { //长度为-1则读取完毕
  694. result.append(new String(buf, 0, len));
  695. }
  696. inputStream.close();
  697. return result.toString();
  698. }
  699. /**
  700. * 删除文件或递归删除目录
  701. * 递归删除目录下的所有文件及子目录下所有文件
  702. */
  703. public static boolean rm(File file) {
  704. if (!file.exists()) {
  705. return false;
  706. } else {
  707. if (file.isDirectory()) {
  708. String[] children = file.list();
  709. if (children != null) {
  710. for (String child : children) {
  711. if (!rm(new File(file, child))) {
  712. return false;
  713. }
  714. }
  715. }
  716. return true;
  717. } else {
  718. return file.delete();
  719. }
  720. }
  721. }
  722. /**
  723. * 删除文件或递归删除目录
  724. * 递归删除目录下的所有文件及子目录下所有文件
  725. */
  726. public static boolean rm(String path) {
  727. return rm(new File(path));
  728. }
  729. // -------------------------------- S --------------------------------
  730. // public static String splicingPath(String... paths) {
  731. // StringBuilder result = new StringBuilder();
  732. // for (int i = 0; i < paths.length; i++) {
  733. // if (i == 0) {
  734. // if ("/".equals(paths[0].charAt(paths.length - 1) + "")) {
  735. // String substring = paths[0].substring(0, paths[0].length() - 2);
  736. // result.append(substring);
  737. // } else {
  738. // result.append(paths[0]);
  739. // }
  740. // } else {
  741. // String[] split = paths[i].split("/");
  742. //
  743. // for (String s : split) {
  744. // if (s != null && !"".equals(s)) {
  745. // result.append("/").append(s);
  746. // }
  747. // }
  748. // }
  749. // }
  750. // return result.toString();
  751. // }
  752. // -------------------------------- T --------------------------------
  753. // -------------------------------- U --------------------------------
  754. // -------------------------------- V --------------------------------
  755. // -------------------------------- W --------------------------------
  756. /**
  757. * 将字符串保存为本地文件
  758. */
  759. @SneakyThrows
  760. public static void writeStringToLocalFile(String string, String filePath) throws IOException {
  761. writeInputStreamToLocalFile(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)), filePath);
  762. }
  763. /**
  764. * 将字符串保存为本地文件
  765. */
  766. @SneakyThrows
  767. public static void writeStringToLocalFile(String string, String filePath, int bufferLength) throws IOException {
  768. writeInputStreamToLocalFile(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)), filePath, bufferLength);
  769. }
  770. /**
  771. * 将输入流保存为本地文件
  772. */
  773. public static void writeInputStreamToLocalFile(InputStream inputStream, String filePath) throws IOException {
  774. writeInputStreamToLocalFile(inputStream, filePath, 4096);
  775. }
  776. /**
  777. * 将输入流保存为本地文件
  778. */
  779. public static void writeInputStreamToLocalFile(InputStream inputStream, String filePath, int bufferLength) throws IOException {
  780. BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
  781. byte[] data = new byte[bufferLength];
  782. int dataLength;
  783. File file = new File(filePath);
  784. createParentDirectory(file);
  785. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file, false));
  786. while ((dataLength = bufferedInputStream.read(data)) != -1) {
  787. bufferedOutputStream.write(data, 0, dataLength);
  788. }
  789. bufferedOutputStream.close();
  790. bufferedInputStream.close();
  791. }
  792. /**
  793. * 将输入流保存为本地文件
  794. */
  795. public static void writeInputStreamToLocalDirectory(InputStream inputStream, String directoryPath, String filename) throws IOException {
  796. BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
  797. byte[] data = new byte[1024];
  798. int dataLength;
  799. File file = new File(directoryPath + File.separator + filename);
  800. createDirectory(directoryPath);
  801. createFile(file);
  802. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file, false));
  803. while ((dataLength = bufferedInputStream.read(data)) != -1) {
  804. bufferedOutputStream.write(data, 0, dataLength);
  805. }
  806. bufferedOutputStream.close();
  807. bufferedInputStream.close();
  808. }
  809. }