FileUtil.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package com.seecoder.dataanalysis.util;
  2. import java.io.*;
  3. /**
  4. * @author miaomuzhi
  5. * @since 2022/1/30
  6. */
  7. public class FileUtil {
  8. private FileUtil() {}
  9. public static boolean writeFile(String path, String content) {
  10. File file = new File(path);
  11. if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {//if parent file doesn't exist and fail to make dir
  12. return false;
  13. }
  14. try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file))) {
  15. if (!file.exists() && !file.createNewFile()) {//if file doesn't exist and program fails to create file
  16. throw new IOException("fail to create file");
  17. }
  18. bufferedWriter.write(content);
  19. bufferedWriter.flush();
  20. return true;
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. return false;
  24. }
  25. }
  26. public static String readFile(String path) {
  27. File file = new File(path);
  28. StringBuilder content = new StringBuilder();
  29. try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
  30. String line;
  31. while ((line = bufferedReader.readLine()) != null)
  32. {
  33. content.append(line).append(System.lineSeparator());
  34. }
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. return new String(content);
  39. }
  40. public static boolean createDirectoryIfAbsent(String path) {
  41. File file = new File(path);
  42. return file.exists() || file.mkdirs();
  43. }
  44. }