我正在根据扩展名搜索文件。现在找到每个文件,想要运行一个命令:
让我们假设找到了文件:C:\Home\1\1.txt
。我的exe存在于:C:\Home\Hello.exe
我想运行类似命令:“C:\Home\Hello.exe C:\Home\1\1.txt
”
同样适用于C:\Home\ABC\2.txt
- “C:\Home\Hello.exe C:\Home\ABC\2.txt
”
请帮助我如何将搜索到的文件作为输入传递给执行命令。
谢谢, 奇诺
答案 0 :(得分:0)
您可以使用以下程序作为基础,然后根据您的要求进一步自定义
public class ProcessBuildDemo {
public static void main(String [] args) throws IOException {
String[] command = {"CMD", "/C", "dir"}; //In place of "dir" you can append the list of file paths that you have
ProcessBuilder probuilder = new ProcessBuilder( command );
//You can set up your work directory
probuilder.directory(new File("c:\\xyzwsdemo")); //This is the folder from where the command will be executed.
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",
Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
让我们开始吧:
使用以下文件过滤文件:FilenameFilter:
http://docs.oracle.com/javase/7/docs/api/java/io/FilenameFilter.html
样品: http://www.java-samples.com/showtutorial.php?tutorialid=384
获得文件后: 使用ProcessBuilder执行:
http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
样品: http://www.xyzws.com/Javafaq/how-to-run-external-programs-by-using-java-processbuilder-class/189
答案 2 :(得分:0)
如果您从命令行运行应用程序(例如windows cmd),并且您的程序名称是Hello.java,那么您只需要输入参数,就像您在示例中所做的那样。所以它看起来像:
java Hello C:\Home\1\1.txt
我没有使用exe,因为这是一个示例,问题标记为“java”标记。
你的Hello.java必须有一个 main 方法,如下所示:
public static void main(String ... args) {
}
参数args
是您在命令行中输入的实际参数。因此,要获取文件名,您必须这样做:
public static void main(String ... args) {
String fileName= args[0];
}
就是这样。稍后,您可以随意使用它,即打开并编辑文件:
File file= new File(fileName);
//do whatever with that file.
答案 3 :(得分:0)
此代码可以帮助您
public static void main(String args[]) {
String filename;
try {
Runtime rt = Runtime.getRuntime();
filename = "";//read the file na,e
Process pr = rt.exec("C:\\Home\\Hello.exe " + filename );
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Error "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}