Java如何基于ProcessBuilder类调用外部程序
demo1
@Test public void testProcessBuilder ( ) { ProcessBuilder processBuilder = new ProcessBuilder ( ) ;
processBuilder. command ( "ipconfig" ) ; processBuilder. redirectErrorStream ( true ) ; try { Process start = processBuilder. start ( ) ; InputStream inputStream = start. getInputStream ( ) ; InputStreamReader inputStreamReader = new InputStreamReader ( inputStream, "gbk" ) ; int len = - 1 ; char [ ] c = new char [ 1024 ] ; StringBuffer outputString = new StringBuffer ( ) ; while ( ( len = inputStreamReader. read ( c) ) != - 1 ) { String s = new String ( c, 0 , len) ; outputString. append ( s) ; System . out. print ( s) ; } inputStream. close ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } }
demo02
@Test public void testFFmpeg ( ) { ProcessBuilder processBuilder = new ProcessBuilder ( ) ; List < String > command = new ArrayList < > ( ) ; command. add ( "D:/program/ffmpeg-20191229-e20c6d9-win64-static/bin/ffmpeg.exe" ) ; command. add ( "-i" ) ; command. add ( "D:/test/video/1.avi" ) ; command. add ( "-y" ) ; command. add ( "-c:v" ) ; command. add ( "libx264" ) ; command. add ( "-s" ) ; command. add ( "1280x720" ) ; command. add ( "-pix_fmt" ) ; command. add ( "yuv420p" ) ; command. add ( "-b:a" ) ; command. add ( "63k" ) ; command. add ( "-b:v" ) ; command. add ( "753k" ) ; command. add ( "-r" ) ; command. add ( "18" ) ; command. add ( "D:/test/video/1.mp4" ) ; processBuilder. command ( command) ; processBuilder. redirectErrorStream ( true ) ; try { Process start = processBuilder. start ( ) ; InputStream inputStream = start. getInputStream ( ) ; InputStreamReader inputStreamReader = new InputStreamReader ( inputStream, "gbk" ) ; int len = - 1 ; char [ ] c = new char [ 1024 ] ; StringBuffer outputString = new StringBuffer ( ) ; while ( ( len = inputStreamReader. read ( c) ) != - 1 ) { String s = new String ( c, 0 , len) ; outputString. append ( s) ; System . out. print ( s) ; } inputStream. close ( ) ; } catch ( IOException e) { e. printStackTrace ( ) ; } }