简体   繁体   English

在Java程序中运行命令行工具

[英]Running command line tools inside of a Java program

Hello StackOverflow Community, 您好StackOverflow社区,

I have this JUnit Tests that need to run a Server with the command mvn exec:java , and I need to delete the contents of a directory before the tests are executed. 我有这个JUnit测试,需要使用命令mvn exec:java运行服务器,并且我需要在执行测试之前删除目录的内容。 Otherwise, the JUnit test will fail. 否则, JUnit测试将失败。 Is there any way I can include these steps into my source code? 有什么办法可以将这些步骤包括在我的源代码中?

Ejay 埃杰

You should use JUnit's @BeforeClass notation which will be called before the first test starts to clean up the target directory. 您应该使用JUnit的@BeforeClass表示法,该表示法将在第一个测试开始之前清理目标目录。 You should also use the commons-io library avoid unnecessary coding. 您还应该使用commons-io库,避免不必要的编码。

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.junit.BeforeClass;
import org.junit.Test;


public class DeleteDirectoryTest {
    private static final String DIRECTORY_PATH = "C:/TEMP";

    @BeforeClass
    public static void cleanUp() throws IOException {
        FileUtils.deleteDirectory(new File(DIRECTORY_PATH));
    }

    @Test
    public void doSomeTest() {
        // Test code goes here
   }
}

您可以在JUnit'@BeforeClass'初始化方法中为目录递归删除

public static boolean emptyDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return true;
}

您可以使用ProcessBuilder从Java应用程序执行命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM