有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个将文件从一个目录复制到另一个目录的应用程序。但是每次我调用该方法复制文件时,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();
    }
}

共 (1) 个答案

  1. # 1 楼答案

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

        new Thread(new Runnable() {
            @Override
            public void run() {
    
            }
        }).start();
    

    把你的方法放进去,就是复制文件的方法

    所以看起来像

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