我想用java写个图形界面的FTP客户端,下面是部分代码:这先说下,client是个Socket对象,代码的目的是从服务器中取得响应并在终端显示出来
InputStream is = client.getInputStream();
BufferedReader response = new BufferedReader(new InputStreamReader(is));
while(true)
{
echo = response.readLine();
if(echo.isEmpty())
break;
else
System.out.println(echo + echo.length());
}
我现在的问题就是if(echo.isEmpty())这个始终无法进行。就是说在response.readLine()无法读到响应的时候echo总是不能break;,然后整个程序就timeout。后来我把红色部分换成echo == null也不行。我在javadoc中看到的当response达到流末端时readLine返回的是null啊……我该怎么办,各位前辈帮帮忙……
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;public class FileReader { public static void main(String[] args) {
InputStream is = null;
BufferedReader response = null;
try {
is = new FileInputStream("d:/1.txt");
response = new BufferedReader(new InputStreamReader(is));
String echo ;
while ((echo = response.readLine()) != null) {
System.out.println(echo);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}}
private void SendCmd(String command)
{
try
{
String echo = " ";
os=client.getOutputStream();
is=client.getInputStream();
send = new PrintWriter(os,true);
response = new BufferedReader(new InputStreamReader(is));
send.write(command + "\r\n");
send.flush();
System.out.println("> " + command);
while((echo = response.readLine())!= null)
{
System.out.println(echo + echo.length());
statusBar.append(echo+"\n");//放到图形界面中的状态栏中
}
response.close();
is.close();
}
catch(NullPointerException ex)
{
ex.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.println("发送信息时出错\n");
}
}
程序运行时其他位置都没问题,不用循环只用单句读readLine()也没问题,但是一旦换成这个循环就会死机,终端输出是没问题的,但是出来的图形界面是死掉的,而且我在主程序中三次调用这个函数发送命令,终端上的显示却只有第一个
都打印出来,看看到底是什么
P.S.readLine如果读不到行尾结束标志或null是会造成阻塞的