我正在编写一个Web应用程序来处理命令行命令并显示输出。 我尝试过使用exec()但它似乎不起作用。
Process process;
process = Runtime.getRuntime().exec(commands);
String line;
is = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = is.readLine()) != null)
out.println(line);
答案 0 :(得分:0)
添加缓冲区和尝试案例,现在效果很好。
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String[] commands = {"date"};
BufferedReader is = null;
BufferedReader es = null;
try
{
Process process;
process = Runtime.getRuntime().exec(commands);
String line;
is = new BufferedReader(new InputStreamReader(process.getInputStream()));
while((line = is.readLine()) != null)
out.println(line);
es = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while((line = es.readLine()) != null)
System.err.println(line);
int exitCode = process.waitFor();
if (exitCode == 0)
out.println("It worked");
else
out.println("Something bad happend. Exit code: " + exitCode);
} //try
catch(Exception e)
{
out.println("Something when wrong: " + e.getMessage());
e.printStackTrace();
} //catch
finally
{
if (is != null)
try { is.close(); } catch (IOException e) {}
if (es != null)
try { es.close(); } catch (IOException e) {}
} //finally
}