在java中执行命令的正确方法是什么

时间:2014-02-08 10:31:43

标签: java

我需要在命令提示符下使用java执行命令。当我在提示符中键入它时,该命令正常工作,并相应地创建了tutorial.mallet文件。但是,当我通过代码执行时,没有任何事情发生。

命令是:

C:\mallet> bin\mallet import-dir --input E:\InputFilesForTopicModeling --output E:\Tutorial\tutorial.mallet --keep-sequence --remove-stopwords

这是我的代码

try {
  Runtime rt=Runtime.getRuntime();
  rt.exec("cmd /c"+ "cd mallet");
  String export=" bin\\mallet import-dir --input E:\\InputFilesForTopicModeling --output E:\\Tutorial\tutorial.mallet --keep-sequence --remove-stopwords";
  rt.exec("cmd /c"+export);
} catch(Exception e) {
  e.printStackTrace();
}

2 个答案:

答案 0 :(得分:2)

您不能像这样更改工作目录,但可以将其指定为exec方法的参数:

rt.exec("bin/mallet import-dir --input E:/InputFilesForTopicModeling --output E:/Tutorial/tutorial.mallet --keep-sequence --remove-stopwords",
    null, new File("C:/mallet"));

答案 1 :(得分:0)

在Java中执行命令的正确方法。

1. Cd YourDirectory  //Go to your directory where you put your Java
    code. Example: cd F:

2. Cd yourJavaProject//Go to your directory where you put your Java
    project. Example :cd JavaProject

3. javac posMain.java //Compile the Java file

4. java posMain //Don't use .java after that you will get your program
    output