private void receive(InputStream in) {

FileOutputStream out = null;
try {
File file = new File("D:/test.txt"); 
out = new FileOutputStream(file); byte[] buf = new byte[SIZE];
int length = in.read(buf);
while(length != -1) {
out.write(buf, 0, length);
out.flush();
length = in.read(buf);
}
System.out.println("xxxx");
我写了这么一个方法,负责接收客户端传过来的消息,并且写入到文件当中。
方法的参数是其他地方传过来的: in = socket.getInputStream();  
但是程序会困在while当中,出不来了。执行不到System.out.println("xxxx");
我用DEBUG跟踪了,最后会停在length = in.read(buf)这里。调试的一些跟进按钮都变灰色了。只能停止程序按钮了。
我不知道是怎么一回儿了。请大家帮忙看看。

解决方案 »

  1.   

    InputStream的read方法是阻塞式方法,当没有数据读入时程序就会停在那里
      

  2.   

    是不是 SIZE出现的问题呢 byte[] buf = new byte[SIZE];
    要不就是 最后循环内的 length = in.read(buf); 好像没必要加这句把 
      

  3.   

    那怎么解决,让其能读完传输过来的数据就跳出while呢?
    当我这样,自己构建一个文件。程序能正常执行完毕呢?private void receive() throws Exception {
    FileInputStream in = new FileInputStream("request.xml");

    FileOutputStream out = null;
    try {
    File file = new File("D:/test.txt"); 
    out = new FileOutputStream(file); byte[] buf = new byte[SIZE];
    int length = in.read(buf);
    while(length != -1) {
    out.write(buf, 0, length);
    out.flush();
    length = in.read(buf);
    }
    System.out.println("xxxx");
      

  4.   

    SIZE, 是程序定义个一个常量  private static final int SIZE = 1024;
    while中的  length = in.read(buf);  肯定要的啊。条件就是根据 length 的值判断的啊。
      

  5.   

    一种方法是数据的发送方发送完数据后再发送一个数据传输结束的标识符,接收端监听这个标识符,收到就跳出while循环另一种方法是用非阻塞通信,不过比较难,你自己看着选吧
      

  6.   


    不明白,不知道如何判定文件是否传输完毕。客户端传读取一个XML文件传过来,怎么判断他是否读取完毕呢?
      

  7.   

    你把客户端的 out.flush(),out.close();应该就不会堵塞了。