Jump to content

Execute a system command: Difference between revisions

m
→‎{{header|Java}}: Highlighting, note about different OSs
m (→‎{{header|C}}: stripped unuseful text (because of the task specification))
m (→‎{{header|Java}}: Highlighting, note about different OSs)
Line 115:
=={{header|Java}}==
{{works with|Java|1.5+}}
<lang javajava5>import java.util.Scanner;
import java.io.*;
 
Line 121:
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX
Scanner sc = new Scanner(p.getInputStream());
while (sc.hasNext()) System.out.println(sc.nextLine());
Line 133:
{{works with|Java|1.4+}}
There are two ways to run system commands. The simple way, which will hang the JVM (I would be interested in some kind of reason). -- this happens because the the inputStream buffer fills up and blocks until it gets read. Moving your .waitFor after reading the InputStream would fix your issue (as long as your error stream doesn't fill up)
<lang java>import java.io.IOException;
<pre>
import java.io.IOException;
import java.io.InputStream;
 
Line 172 ⟶ 171:
}</lang>
}
</pre>
 
And the right way, which uses threading to read the InputStream given by the process.
<lang java>import java.io.IOException;
<pre>
import java.io.IOException;
import java.io.InputStream;
 
Line 240 ⟶ 237:
}
}
}</lang>
}
</pre>
 
=={{header|Logo}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.