Runtime.getRuntime().exec(is.readLine());遇到问题

程序没报错,执行到Runtime.getRuntime().exec(is.readLine());时没看到任何效果,也不继续执行接下来的代码。is.readLine() 是"cmd /k start E://test.txt"。

public class Server {
public static void main(String [] args) {
try {
ServerSocket sersoc = null;
try {
sersoc = new ServerSocket(8399);
} catch (Exception e) {
// TODO: handle exception
}
Socket socket = null;
try {
socket = sersoc.accept();
} catch (Exception e) {
System.out.println("Error."+e);
}
String line = null;
BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter os = new PrintWriter(socket.getOutputStream());
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));

        System.out.println(is.readLine());
        Runtime.getRuntime().exec(is.readLine());

        while(!line.equals("bye")){
            os.println(line);
            System.out.println("Server:" + line);
            System.out.println("Client:" + is.readLine());
            line = sin.readLine();
        }
        os.close();
        is.close();
        sersoc.close();
        socket.close();
    }catch (Exception e) {
        // TODO: handle exception
        System.out.println(e);
    }
}

}

不能使用两次readLine方法,因为第一次已经读取了内容,下次exec的时候是处于等待输入的状态,他读取不出来了,所以没有执行,会一直等待输入。解决办法就是第一次读取的时候将其转换为变量,修改如下:

String command = is.readLine();
System.out.println(command);
Runtime.getRuntime().exec(command);

修改为上面的即可执行操作了,前提是你的command已经传过来了啊。

你这个代码只是server端的,看不到你的client端是怎么写的,因此需要你确保能够读取到你client端输入的命令。

另外你的代码中,line直接赋值了null,是不对的,即使你执行了命令,在下面的while判断中也会报空指针的,这一行代码:

while(!line.equals("bye")) 

将line初始化修改一下。

此外,不建议使用BufferedReader方法来读取client端传送的内容,因为你要在client中输入命令的话,必须手动加上

\r\n 

否则server端读取不到你输入的命令,readLine是以换行符为读取结束的。你可以参考下这个里面介绍的读写方法。http://www.cnblogs.com/xignzou/p/3202346.html

is.readLine()有输入时才能往下执行,不然就阻塞等待。
 System.out.println(is.readLine());//这里读取输入数据了
        Runtime.getRuntime().exec(is.readLine());//这里读取不到了,只能等待
改成
String str = is.readLine();
 System.out.println(str);
        Runtime.getRuntime().exec(str);

可以的,看下路径。路径用反斜杠\

http://blog.sina.com.cn/s/blog_3d731e9001000ajm.html

可以的,看下路径。路径用反斜杠\\

可用局部变量替代is.readline()

先判断System.out.println(is.readLine());这句有输出吗,然后再一步一步判断