0

我正在根据扩展名搜索文件。现在对于找到的每个文件,要运行一个命令:

让我们假设找到文件: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"

请帮助我如何将搜索到的文件作为输入传递以执行命令。

谢谢,奇诺

4

4 回答 4

0

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();
    }
 }
}
于 2013-06-13T10:53:44.097 回答
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.
于 2013-06-13T10:55:39.983 回答
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();
            }
        }
于 2013-06-13T11:47:45.650 回答