Recently do a group purchase file download service, their lazy do not want to write the logic of the file download, and Linux Curl command is very powerful, so want to directly through the Java to execute Curl command to do the download.
In Java, you can execute external shell commands by Runtime.getruntime (). Exec.
Process proc = Runtime.getruntime (). EXEC ("ping www.baidu.com");
InputStream in = Proc.getinputstream ();
BufferedReader br = new BufferedReader (new InputStreamReader (in, "GBK"));
String line = null;
while ((Line=br.readline ())!=null) {
System.out.println (line);
}
The following is an example of performing a simple ping command and printing its output.
Package com.ricky.java.sms;
Import Java.io.BufferedReader;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
public class Runtimetest {public static void main (string[] args) {//MethodA ();
MethodB ();
public static void MethodB () {BufferedReader br = null;
try {Process proc = runtime.getruntime (). EXEC ("ping www.baidu.com");
InputStream in = Proc.getinputstream ();
br = new BufferedReader (new InputStreamReader (in, "GBK"));
String line = null;
while ((Line=br.readline ())!=null) {System.out.println (line);
} catch (IOException e) {e.printstacktrace ();
}finally{if (br!=null) {try {br.close ();
catch (IOException e) {e.printstacktrace ();
}}} public static void MethodA () {inputstream in = null;
try {Process proc = runtime.getruntime (). EXEC ("ping www.baidu.com"); in = Proc.getinPutstream ();
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
in = Proc.getinputstream ();
byte[] buf = new byte[1024];
int len = 0;
while (len = In.read (buf, 0, 1024))!=-1) {baos.write (buf, 0, Len);
} byte[] arr = Baos.tobytearray ();
string result = new String (arr, "GBK");
System.out.println ("result=" +result);
catch (IOException e) {e.printstacktrace ();
}finally{if (in!=null) {try {in.close ();
catch (IOException e) {e.printstacktrace ();
}
}
}
}
}
The results of the printing are as follows:
Ping www.a.shifen.com [180.149.131.205] has 32 bytes of data:
Reply from 180.149.131.205: Byte =32 time =1ms ttl=56
Reply from 180.149.131.205: Byte =32 time =1ms ttl=56
Reply from 180.149.131.205: Byte =32 time =1ms ttl=56
Reply from 180.149.131.205: Byte =32 time =1ms ttl=56
Ping Statistics for 180.149.131.205:
Packet: Sent = 4, received = 4, lost = 0 (0% lost),
Estimated time, in milliseconds, for a round trip:
Shortest = 1ms, longest = 1ms, average = 1ms