From 0177d6a1cf0307055e4b0d33d597298d2c86cb06 Mon Sep 17 00:00:00 2001 From: Josscoder Date: Tue, 10 Jan 2023 12:51:50 -0500 Subject: [PATCH] feat: change file utils algorithms for improvide optimization --- pom.xml | 5 ++ .../jessentials/utils/FileUtils.java | 65 +++++++++---------- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/pom.xml b/pom.xml index e8b6f2a..ddadb4d 100644 --- a/pom.xml +++ b/pom.xml @@ -103,5 +103,10 @@ ac7e2c7580 compile + + commons-io + commons-io + 2.11.0 + \ No newline at end of file diff --git a/src/main/java/me/josscoder/jessentials/utils/FileUtils.java b/src/main/java/me/josscoder/jessentials/utils/FileUtils.java index b40b068..03cba04 100644 --- a/src/main/java/me/josscoder/jessentials/utils/FileUtils.java +++ b/src/main/java/me/josscoder/jessentials/utils/FileUtils.java @@ -1,47 +1,42 @@ package me.josscoder.jessentials.utils; -import java.io.*; -import java.nio.file.Files; +import java.io.File; +import java.io.IOException; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; public class FileUtils { - public static void copy(File source, File destination) throws IOException { - if (source.isDirectory()) { - if (!destination.exists()) destination.mkdir(); - - String[] files = source.list(); - if (files == null) return; - - for (String file : files) { - File newSource = new File(source, file); - File newDestination = new File(destination, file); - copy(newSource, newDestination); - } - } else { - InputStream inputStream = Files.newInputStream(source.toPath()); - OutputStream outputStream = Files.newOutputStream(destination.toPath()); - - byte[] buffer = new byte[1024]; - - int length; - - while ((length = inputStream.read(buffer)) > 0) { - outputStream.write(buffer, 0, length); - } - - inputStream.close(); - outputStream.close(); + public static void copy(File srcDir, File destDir) { + try { + org.apache.commons.io.FileUtils.copyDirectory(srcDir, destDir, true); + } catch (IOException e) { + e.printStackTrace(); } } public static void delete(File file) { - if (file.isDirectory()) { - File[] files = file.listFiles(); - if (files == null) return; - - for (File child : files) delete(child); + try { + Path dir = file.toPath(); + Files.walkFileTree(dir, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + if (exc == null) { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } else { + throw exc; + } + } + }); + } catch (IOException e) { + e.printStackTrace(); } - - file.delete(); } }