Приложение зависает при запуске метода - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть приложение, которое копирует файлы из одного каталога в другой. Но каждый раз, когда я вызываю метод для копирования файлов, пользовательский интерфейс (окно) останавливается, пока они не будут скопированы. У тебя есть идеи почему? Неважно, сколько файлов в каталоге, так как он всегда зависает. Это мой код:

public void startProcess(File orgDir, File destDir) {
    Screen1Controller sf = new Screen1Controller();
    int y = 1;
    try {
        File[] files = orgDir.listFiles();
        for (File file : files) {
            if (file.isDirectory() == false) {
                File destinationPath = new File(destDir.getCanonicalPath() + "\\");
                destDir = new File(destinationPath + "\\" + "");
                destDir.mkdir();
                System.out.println("file:" + file.getCanonicalPath());
                try {
                    String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", "");
                    File destFile = new File(destDir.getPath() + "\\" + file.getName());
                    if (Files.exists(Paths.get(destFile.getPath()))) {
                        System.out.println("There is a duplicate.");
                        File[] destFiles = destDir.listFiles();
                        for (File destinationFile : destFiles) {
                            if (destinationFile.getName().startsWith(fileNameWithOutExt)) {
                                y++;
                            }
                        }
                        File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y);

                        file.renameTo(newFile);
                        File destPath = new File(destDir.getPath() + "\\" + newFile.getName());
                        System.out.println(newFile.getCanonicalPath());
                        Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath()));

                        newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt));
                    } else {
                        Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                startProcess(file, destDir);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

1 Ответ

0 голосов
/ 02 ноября 2018

Вы должны создать новый поток, чтобы обрабатывать копирование в новом потоке, а не в потоке пользовательского интерфейса

    new Thread(new Runnable() {
        @Override
        public void run() {

        }
    }).start();

Поместите свой метод внутрь того, который копирует файлы.

так бы это выглядело как

    new Thread(() -> {
        startProcess(... , ...);
    }).start();
...