java 为什么 ByteArrayInputStream 没有返回预期的结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7498067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why does ByteArrayInputStream doesn't return expected results?
提问by Shera
I am trying to interact with an application in windows server through telnet, so I am using TelnetClient() method. I could interact (send commands and retrieve results) using System.in.read(), however I want this program to run automatically without using any keyboard inputs. So, my question is, why does System.in.read() works, yet ByteArrayInputStream doesn't?
我试图通过 telnet 与 windows 服务器中的应用程序交互,所以我使用 TelnetClient() 方法。我可以使用 System.in.read() 进行交互(发送命令和检索结果),但是我希望该程序无需使用任何键盘输入即可自动运行。所以,我的问题是,为什么 System.in.read() 起作用,而 ByteArrayInputStream 不起作用?
This is my code so far :
到目前为止,这是我的代码:
public class telnetExample2 implements Runnable, TelnetNotificationHandler{
static TelnetClient tc = null;
public static void main (String args[]) throws IOException, InterruptedException{
tc = new TelnetClient();
while (true){
try{
tc.connect("192.168.1.13", 8999);
}
catch (SocketException ex){
Logger.getLogger(telnetExample2.class.getName()).log(Level.SEVERE, null,ex);
}
Thread reader = new Thread(new telnetExample2());
tc.registerNotifHandler(new telnetExample2());
String command = "getversion"; //this is the command i would like to write
OutputStream os = tc.getOutputStream();
InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8")); //i'm using UTF-8 charset encoding here
byte[] buff = new byte[1024];
int ret_read = 0;
do{
ret_read = is.read(buff);
os.write(buff, 0, 10)
os.flush();
while(ret_read>=0);
}
}
public void run(){
InputStream instr = tc.getInputStream();
try{
byte[] buff = new byte[1024];
int ret_read = 0;
do{
ret_read = instr.read(buff);
if(ret_read >0){
System.out.print(new String(nuff, 0, ret_read));
}
while(ret_read>=0);}
catch(Exception e){
System.err.println("Exception while reading socket:" + e.getMessage());
}
}
public void receiveNegotiation(int i, int ii){
throw new UnsupportedOperationException("Not supported");
}
}
回答by user207421
InputStream is = new ByteArrayInputStream(command.getBytes("UTF-8")); //i'm using UTF-8 charset encoding here
byte[] buff = new byte[1024];
int ret_read = 0;
do{
ret_read = is.read(buff);
os.write(buff, 0, 10)
os.flush();
while(ret_read>=0);
}
You can reduce those 9 lines that don't work to os.write(command.getBytes("UTF-8"));
which does.
您可以减少那 9 行os.write(command.getBytes("UTF-8"));
不起作用的行。
Why you thought that reading up to 1024 bytes into a buffer and then writing out only the first ten of them was ever going to work is a mystery.
为什么您认为将多达 1024 个字节读入缓冲区然后只写出其中的前十个字节会起作用,这是一个谜。