У меня есть приложение, которое копирует несколько файлов из каталога в определенный пункт назначения. Проблема в том, что при выборе большой папки она становится более интенсивной для самого приложения, а затем вылетает. Есть ли способ сделать так, чтобы он не разбился? Может быть, разбить его на более мелкие части?
Это мой код:
public void startProcess(File orgDir, File destDir) {
Screen1Controller sf = new Screen1Controller();
String selectedExtension = sf.selectedExtension; // Gets selected extension from Screen1
String extensionType = sf.typeOfExtension; // Gets selected extension type from Screen1
int y = 1; // This is for searching for duplicates.. See below.
try {
File[] files = orgDir.listFiles();
for (File file : files) { // Goes through the files in the given directory
if (!file.isDirectory() && file.getName().endsWith(selectedExtension)){
File destinationPath = new File(destDir.getCanonicalPath() + "\\");
destDir = new File(destinationPath + "\\" + extensionType); // Sets the destination path
destDir.mkdir();
System.out.println("file:" + file.getCanonicalPath()); // Prints the file path
try{
String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", ""); // Gets the current file without the extension
File destFile = new File(destDir.getPath() + "\\" + file.getName()); // If a file of the same name exists in the dest folder
if (Files.exists(Paths.get(destFile.getPath()))) // Checks if there is a file with the same name in the folder
{
System.out.println("There is a duplicate.");
File[] destFiles = destDir.listFiles();
for (File destinationFile : destFiles) // Searches through the destination folder
{
if(destinationFile.getName().startsWith(fileNameWithOutExt)){ // Checks if the selected file has the same name as the file that's going to be moved.
y++; // Increments y by 1 to keep track of how many there are of the same/similar name
}
}
File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y + selectedExtension); // Creates a new file with new name.
file.renameTo(newFile); // Renames to a unique name and moves the file to the destination folder
File destPath = new File(destDir.getPath() + "\\" + newFile.getName()); // Gets the destination path for the file
System.out.println(newFile.getCanonicalPath());
Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath())); // Renames the original file back to its original name
newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt + selectedExtension));
} else {
Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath())); // Moves the file to the destination folder
}
}catch(Exception e){
e.printStackTrace();
}
} else{
startProcess(file, destDir);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}