SmartFileUtil.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package net.lab1024.smartadmin.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.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.OutputStreamWriter;
  11. import java.nio.charset.Charset;
  12. import org.apache.commons.io.FileUtils;
  13. /**
  14. * @author zhuoda
  15. */
  16. public class SmartFileUtil extends FileUtils {
  17. public static boolean isXmlFile(File file) {
  18. return "xml".equalsIgnoreCase(getFileExtension(file.getName()));
  19. }
  20. /**
  21. * 文件后缀名
  22. *
  23. * @param fullName
  24. * @return
  25. */
  26. public static String getFileExtension(String fullName) {
  27. String fileName = new File(fullName).getName();
  28. int dotIndex = fileName.lastIndexOf('.');
  29. return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
  30. }
  31. /**
  32. * 不带后缀名的文件名
  33. *
  34. * @param file
  35. * @return
  36. */
  37. public static String getNameWithoutExtension(String file) {
  38. String fileName = new File(file).getName();
  39. int dotIndex = fileName.lastIndexOf('.');
  40. return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
  41. }
  42. public static boolean isFileExist(String filePath) {
  43. File file = new File(filePath);
  44. return file.exists();
  45. }
  46. /**
  47. * 验证文件是否存在,如果不存在则抛出异常
  48. *
  49. * @param filePath
  50. * @throws IOException
  51. */
  52. public static void isFileExistThrowException(String filePath) throws IOException {
  53. File file = new File(filePath);
  54. if (!file.exists()) {
  55. throw new FileNotFoundException(filePath);
  56. }
  57. }
  58. public static BufferedReader newBufferedReader(File file, Charset charset) throws FileNotFoundException {
  59. return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
  60. }
  61. public static BufferedWriter newBufferedWriter(File file, Charset charset) throws FileNotFoundException {
  62. return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
  63. }
  64. public static boolean createParentDirs(File file) throws IOException {
  65. File parent = file.getCanonicalFile().getParentFile();
  66. if (parent == null) {
  67. return false;
  68. }
  69. return parent.mkdirs();
  70. }
  71. public static boolean createNotExistParentDirFile(File file) throws IOException {
  72. boolean createParentDirsRes = createParentDirs(file);
  73. if (!createParentDirsRes) {
  74. throw new IOException("cannot create parent Directory of " + file.getName());
  75. }
  76. return file.createNewFile();
  77. }
  78. }