java吧 关注:1,235,656贴子:12,703,175
  • 10回复贴,共1

java传输文件的问题

只看楼主收藏回复

当我客户端与服务器点对点传输时没有问题,但是我服务器用多线程接收就不能完整的接收文件,服务器有两个线程,一个是in.readUTF();接收字符串消息,另一个是in.read(byte[])接收文件转化的byte数组,两个线程都是时时监听,如果我只有一个in.read(byte[])接收文件线程就不会出现问题,现在两个线程报错
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
at java.io.DataInputStream.readUTF(Unknown Source)
求大神解释啊


1楼2014-12-01 19:54回复
    public void run(){
    byte[] a = new byte[1024];
    int nu = 0;
    try {
    while((nu = in.read(a))!=-1){
    System.out.println("nu "+nu);
    output.write(a, 0, nu);
    }
    b = output.toByteArray();
    System.out.println("b "+b.length);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    byte2image(b);
    }
    public void byte2image(byte[] data){
    if(data.length<3) return;
    try{
    FileImageOutputStream imageOutput = new FileImageOutputStream(new File("C:\\Users\\Administrator\\Desktop\\文件接收\\1.jpg"));
    imageOutput.write(data, 0, data.length);
    imageOutput.close();
    System.out.println("Make Picture success,Please find image in " + "C:/Users/Administrator/Desktop");
    } catch(Exception ex) {
    System.out.println("Exception: " + ex);
    ex.printStackTrace();
    }
    }


    2楼2014-12-01 19:55
    收起回复
      public class Send {
      public static void main(String[] args){
      FileImageInputStream input = null;
      try {
      Socket s = new Socket("113.251.167.236",6668);
      DataOutputStream out = new DataOutputStream(s.getOutputStream());
      input = new FileImageInputStream(new File("C:/Users/Administrator/Desktop/文件传输/1.jpg"));
      int numBytesRead = 0;
      int c = 0;
      byte[] a = new byte[1024];
      while ((numBytesRead = input.read(a)) != -1) {
      System.out.println(numBytesRead);
      c = c+numBytesRead;
      out.write(a, 0, numBytesRead);
      out.flush();
      }
      out.writeUTF("www");
      System.out.println("c "+c);
      out.flush();
      out.close();
      s.close();
      } catch (UnknownHostException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      }
      }
      }


      3楼2014-12-01 19:56
      收起回复
        EOFException这个异常也许你看过API。
        你可以把你传输的数据最后加一个标识,比如NULL,接收端判断如果是NULL就表示读取完毕。
        举个例子,a.txt
        123
        456
        23
        NULL --表示读取完毕的标识
        读取的时候直接判断这个标识


        4楼2014-12-01 20:20
        收起回复
          不清楚


          来自Android客户端5楼2014-12-01 20:33
          回复