我正在根据扩展名搜索文件。现在对于找到的每个文件,要运行一个命令:
让我们假设找到文件: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
"
请帮助我如何将搜索到的文件作为输入传递以执行命令。
谢谢,奇诺
我正在根据扩展名搜索文件。现在对于找到的每个文件,要运行一个命令:
让我们假设找到文件: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
"
请帮助我如何将搜索到的文件作为输入传递以执行命令。
谢谢,奇诺
You can use below program as a base and then customize further as per your rqeuirement
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();
}
}
}
让您开始:
过滤文件使用: 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
如果您从命令行(例如 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.
此代码将帮助您
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();
}
}