由于前段时间一个网友写信询问如何在运行其他可执行程序时将控制台的输入提交到它想运行的程序,由于考虑到他的特殊情况就帮他弄了一下,刚开始想着这个问题应该比较简单,但是在实际做的过程中才发现有很多陷阱,而且好像不能弄一个非常通用的东西出来。 下面的代码是我想做出的一个通用封装器的尝试:
import java.io.*;
public class commandwrapper
{
process process;
thread in;
thread out;
public commandwrapper(process process)
{
this.process = process;
final inputstream inputstream
= process.getinputstream();
//final bufferedreader
r=new bufferedreader
(new inputstreamreader(inputstream));
final byte[] buffer = new byte[1024];
out = new thread()
{
//string line;
int linenumber=0;
public void run()
{
try {
while (true)
{
int count = inputstream.read(buffer);
system.out.println
(linenumber+":"+new string
(buffer, 0, count-1));
//line=r.readline();
//system.out.println
(linenumber+":"+line);
linenumber++;
}
}
catch (exception e)
{
}
}
};
final bufferedreader reader =
new bufferedreader
(new inputstreamreader(system.in));
final outputstream outputstream
= process.getoutputstream();
in = new thread()
{
string line;
public void run()
{
try {
while (true)
{
outputstream.write(
(reader.readline()+"\n").getbytes());
outputstream.flush();
}
}
catch (exception e)
{
}
}
};
}
public void startin()
{
in.start();
}
public void startout()
{
out.start();
}
public void interruptin()
{
in.interrupt();
}
public void interruptout()
{
out.interrupt();
}
public static void main(string[] args)
{
try
{
commandwrapper command =
new commandwrapper(runtime.getruntime().
exec("native2ascii"));
command.startin();
command.startout();
}
catch (exception e) {
e.printstacktrace();
}
}
}
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器