Java 应用程序在运行方法时冻结

Java 应用程序在运行方法时冻结,java,freeze,Java,Freeze,我有一个将文件从一个目录复制到另一个目录的应用程序。但是每次我调用该方法复制文件时,UI(窗口)都会冻结,直到复制完成。你知道为什么吗?目录中有多少文件并不重要,因为它总是冻结。 这是我的代码: public void startProcess(File orgDir, File destDir) { Screen1Controller sf = new Screen1Controller(); int y = 1; try { File[] files

我有一个将文件从一个目录复制到另一个目录的应用程序。但是每次我调用该方法复制文件时,UI(窗口)都会冻结,直到复制完成。你知道为什么吗?目录中有多少文件并不重要,因为它总是冻结。 这是我的代码:

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();
    }
}

您必须创建一个新线程来处理新线程中的复制,而不是UI线程

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

        }
    }).start();
把你的方法放进去,就是复制文件的方法

所以看起来像是

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

您正在使用什么GUI库?摆动JavaFX?1)要更快地获得更好的帮助,请发布或。2) 不要阻止EDT(事件调度线程)。发生这种情况时,GUI将“冻结”。有关详细信息和修复方法,请参阅。