FileGet.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package migl.util;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.charset.StandardCharsets;
  5. import java.nio.file.Files;
  6. import java.nio.file.Paths;
  7. import java.util.stream.Stream;
  8. public class FileGet {
  9. private File file;
  10. private String before;
  11. public FileGet(String path) {
  12. this(path, "");
  13. }
  14. public FileGet(String path, String before) {
  15. this.file = new File(path);
  16. this.before = before;
  17. }
  18. public boolean exists() {
  19. return this.file.exists();
  20. }
  21. public boolean findFile(String fileName) {
  22. if(!this.exists()) {
  23. return false;
  24. }
  25. File[] files = this.file.listFiles();
  26. for(File f : files) {
  27. if(f.getName().equals(fileName)) {
  28. this.file = f;
  29. return true;
  30. }
  31. }
  32. return false;
  33. }
  34. public String getFiles() {
  35. if(!this.exists()) {
  36. return null;
  37. }
  38. if(!this.file.isDirectory()) {
  39. return this.getContent();
  40. }
  41. StringBuilder sb = new StringBuilder(this.before);
  42. File[] files = this.file.listFiles();
  43. for(File f : files) {
  44. sb.append(f.getName() + "\n");
  45. }
  46. return sb.toString();
  47. }
  48. public String getContent() {
  49. if(!this.exists()) {
  50. return null;
  51. }
  52. if(!this.file.isFile()) {
  53. return this.getFiles();
  54. }
  55. StringBuilder sb = new StringBuilder(this.before);
  56. try(Stream<String> stream = Files.lines(Paths.get(this.file.getAbsolutePath()), StandardCharsets.UTF_8)){
  57. stream.forEach(s -> sb.append(s + "\n"));
  58. } catch(IOException ex) {
  59. return null;
  60. }
  61. return sb.toString();
  62. }
  63. }