简体   繁体   中英

Running command line tools inside of a Java program

Hello StackOverflow Community,

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. Otherwise, the JUnit test will fail. 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. You should also use the commons-io library avoid unnecessary coding.

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应用程序执行命令

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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