FileUtils.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. package com.izouma.awesomeAdmin.utils;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.io.*;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.attribute.PosixFileAttributeView;
  7. import java.nio.file.attribute.PosixFileAttributes;
  8. import java.nio.file.attribute.PosixFilePermission;
  9. import java.nio.file.attribute.PosixFilePermissions;
  10. import java.util.Set;
  11. import java.util.zip.ZipEntry;
  12. import java.util.zip.ZipInputStream;
  13. public class FileUtils {
  14. public static String getExtension(String fileName) {
  15. if (StringUtils.INDEX_NOT_FOUND == StringUtils.indexOf(fileName, "."))
  16. return StringUtils.EMPTY;
  17. String ext = StringUtils.substring(fileName, StringUtils.lastIndexOf(fileName, "."));
  18. return StringUtils.trimToEmpty(ext);
  19. }
  20. public static String getFileName(String header) {
  21. String[] tempArr1 = header.split(";");
  22. String[] tempArr2 = tempArr1[2].split("=");
  23. // 获取文件名,兼容各种浏览器的写法
  24. return tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
  25. }
  26. /**
  27. * 获取文件权限
  28. *
  29. * <pre>
  30. * 当前仅支持posix系统,需要修改为windows格式
  31. * </pre>
  32. *
  33. * @param path
  34. * @return
  35. * @throws IOException
  36. */
  37. public static String getPermissions(Path path) throws IOException {
  38. PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class);
  39. PosixFileAttributes readAttributes = fileAttributeView.readAttributes();
  40. Set<PosixFilePermission> permissions = readAttributes.permissions();
  41. return PosixFilePermissions.toString(permissions);
  42. }
  43. /**
  44. * 修改文件权限
  45. *
  46. * @param file
  47. * @param permsCode
  48. * @param recursive
  49. * @return
  50. * @throws IOException
  51. */
  52. public static String setPermissions(File file, String permsCode, boolean recursive) throws IOException {
  53. PosixFileAttributeView fileAttributeView = Files.getFileAttributeView(file.toPath(),
  54. PosixFileAttributeView.class);
  55. fileAttributeView.setPermissions(PosixFilePermissions.fromString(permsCode));
  56. if (file.isDirectory() && recursive && file.listFiles() != null) {
  57. for (File f : file.listFiles()) {
  58. setPermissions(f, permsCode, true);
  59. }
  60. }
  61. return permsCode;
  62. }
  63. public static boolean write(InputStream inputStream, File f) {
  64. boolean ret = false;
  65. try (OutputStream outputStream = new FileOutputStream(f)) {
  66. int read;
  67. byte[] bytes = new byte[1024];
  68. while ((read = inputStream.read(bytes)) != -1) {
  69. outputStream.write(bytes, 0, read);
  70. }
  71. ret = true;
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. } finally {
  75. if (inputStream != null) {
  76. try {
  77. inputStream.close();
  78. } catch (IOException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. }
  83. return ret;
  84. }
  85. public static void mkFolder(String fileName) {
  86. File f = new File(fileName);
  87. if (!f.exists()) {
  88. f.mkdir();
  89. }
  90. }
  91. public static File mkFile(String fileName) {
  92. File f = new File(fileName);
  93. try {
  94. f.createNewFile();
  95. } catch (IOException e) {
  96. e.printStackTrace();
  97. }
  98. return f;
  99. }
  100. public static void fileProber(File dirFile) {
  101. File parentFile = dirFile.getParentFile();
  102. if (!parentFile.exists()) {
  103. // 递归寻找上级目录
  104. fileProber(parentFile);
  105. parentFile.mkdir();
  106. }
  107. }
  108. /**
  109. * 将文本文件中的内容读入到buffer中
  110. *
  111. * @param buffer buffer
  112. * @param filePath 文件路径
  113. * @throws IOException 异常
  114. * @date 2013-1-7
  115. */
  116. public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
  117. InputStream is = new FileInputStream(filePath);
  118. String line; // 用来保存每行读取的内容
  119. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  120. line = reader.readLine(); // 读取第一行
  121. while (line != null) { // 如果 line 为空说明读完了
  122. buffer.append(line); // 将读到的内容添加到 buffer 中
  123. buffer.append("\n"); // 添加换行符
  124. line = reader.readLine(); // 读取下一行
  125. }
  126. reader.close();
  127. is.close();
  128. }
  129. /**
  130. * 读取文本文件内容
  131. *
  132. * @param filePath 文件所在路径
  133. * @return 文本内容
  134. * @throws IOException 异常
  135. * @date 2013-1-7
  136. */
  137. public static String readFile(String filePath) throws IOException {
  138. StringBuffer sb = new StringBuffer();
  139. FileUtils.readToBuffer(sb, filePath);
  140. return sb.toString();
  141. }
  142. /**
  143. * 功能:Java读取txt文件的内容
  144. * 步骤:1:先获得文件句柄
  145. * 2:获得文件句柄当做是输入一个字节码流,需要对这个输入流进行读取
  146. * 3:读取到输入流后,需要读取生成字节流
  147. * 4:一行一行的输出。readline()。
  148. * 备注:需要考虑的是异常情况
  149. */
  150. public static String readFileToString(File file) {
  151. try {
  152. if (file.isFile() && file.exists()) { //判断文件是否存在
  153. Long filelength = file.length(); // 获取文件长度
  154. byte[] filecontent = new byte[filelength.intValue()];
  155. try {
  156. FileInputStream in = new FileInputStream(file);
  157. in.read(filecontent);
  158. in.close();
  159. } catch (FileNotFoundException e) {
  160. e.printStackTrace();
  161. } catch (IOException e) {
  162. e.printStackTrace();
  163. }
  164. String fileContentArr = new String(filecontent);
  165. return fileContentArr;// 返回文件内容,默认编码
  166. } else {
  167. System.out.println("找不到指定的文件");
  168. }
  169. } catch (Exception e) {
  170. System.out.println("读取文件内容出错");
  171. e.printStackTrace();
  172. }
  173. return null;
  174. }
  175. public static void unzip(InputStream in, File destDir) throws IOException {
  176. byte[] buffer = new byte[1024];
  177. ZipInputStream zis = new ZipInputStream(in);
  178. ZipEntry zipEntry = zis.getNextEntry();
  179. while (zipEntry != null) {
  180. File newFile = newFile(destDir, zipEntry);
  181. if (zipEntry.isDirectory()) {
  182. if (!newFile.isDirectory() && !newFile.mkdirs()) {
  183. throw new IOException("Failed to create directory " + newFile);
  184. }
  185. } else {
  186. // fix for Windows-created archives
  187. File parent = newFile.getParentFile();
  188. if (!parent.isDirectory() && !parent.mkdirs()) {
  189. throw new IOException("Failed to create directory " + parent);
  190. }
  191. // write file content
  192. FileOutputStream fos = new FileOutputStream(newFile);
  193. int len;
  194. while ((len = zis.read(buffer)) > 0) {
  195. fos.write(buffer, 0, len);
  196. }
  197. fos.close();
  198. }
  199. zipEntry = zis.getNextEntry();
  200. }
  201. zis.closeEntry();
  202. zis.close();
  203. }
  204. public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
  205. File destFile = new File(destinationDir, zipEntry.getName());
  206. String destDirPath = destinationDir.getCanonicalPath();
  207. String destFilePath = destFile.getCanonicalPath();
  208. if (!destFilePath.startsWith(destDirPath + File.separator)) {
  209. throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
  210. }
  211. return destFile;
  212. }
  213. public static File findExcel(File dir) {
  214. if (!(dir.exists() && dir.isDirectory())) return null;
  215. for (File file : dir.listFiles()) {
  216. String name = file.getName().toLowerCase();
  217. if ((name.endsWith(".xlsx") || name.endsWith(".xls")) && !name.startsWith(".") && !file.isHidden()) {
  218. return file;
  219. }
  220. }
  221. return null;
  222. }
  223. }