Java 调用系统命令
ProcessBuilder
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; public class StartProcess { public void startProcessNormal() throws IOException{ ProcessBuilder pb=new ProcessBuilder("cmd.exe","/c","ipconfig","/all"); Process process=pb.start(); InputStream inputStream=process.getInputStream(); Files.copy(inputStream, Paths.get("netstat.txt"), StandardCopyOption.REPLACE_EXISTING); } public void startProcessBasedOnJava7() throws IOException{ ProcessBuilder pb=new ProcessBuilder("cmd.exe","/c","dir"); pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); pb.start(); } public void startProcessBasedOnJava7_1() throws IOException{ ProcessBuilder pb=new ProcessBuilder("cmd.exe","/c","dir"); File output=Paths.get("dir.txt").toFile(); pb.redirectOutput(output); pb.start(); } public static void main(String[] args){ StartProcess sp=new StartProcess(); try { // sp.startProcessNormal(); // sp.startProcessBasedOnJava7(); sp.startProcessBasedOnJava7_1(); } catch (IOException e) { e.printStackTrace(); } } }