在java中调用Runtime运行Linux的重定向的解决方法

一般来说直接接在Linux上运行重定向命令是没有问题的。但是通过java的Runtime类运行命令时不成功。

通常有两种解决办法:

方法一:

    把Runtime.exec()返回的结果Process可以获取到写入流中。
        Process process = runtime.exec(command);
        InputStreamReader is = new InputStreamReader(process.getInputStream());
        BufferedReader br = new BufferedReader(is);
        String line = null;
        while((line = br.readLine())!=null){
            System.out.println(line); 
        }

也可以通过文件输出流输出到本地。

方法二:

直接执行Runtime.getRuntime().exec(mysqldump -uusername -ppassword -hhost -P1800 –databases gxt_main_db –tables mac_summary –no-create-info –where=’mac=52242000447’ >>/home/workspace/test/files/sql_files/mac_summary.sql);

不会有结果产生。

因为exec不能加入重定向和管道符号。

改成如下执行

String[] command = {“sh”,”-c”,”mysqldump -uusername -ppassword -hhost -P1800 –databases gxt_main_db –tables mac_summary –no-create-info –where=’mac=52242000447’ >>/home/workspace/test/files/sql_files/mac_summary.sql”}

Runtime.getRuntime().exec(command)

问题就可以得到解决!

猜你喜欢

转载自blog.csdn.net/chang1120789537/article/details/81168523
今日推荐