我正在尝试将图片从PC发送到Android手机,但我在发送图片时遇到问题。我在这里发布正在发送图片的Java应用程序的代码。

 public void send(OutputStream os) throws Exception{
  // sendfile
  File myFile = new File ("E:\\a.png");
  System.out.println("the file is read");
  byte [] mybytearray  = new byte [(int)myFile.length()+1];
  FileInputStream fis = new FileInputStream(myFile);
  BufferedInputStream bis = new BufferedInputStream(fis);
  bis.read(mybytearray,0,mybytearray.length);
  System.out.println("Sending...");
  os.write(mybytearray,0,mybytearray.length);
  os.flush();
  }


上面的代码只是在端口上写入文件。

这是实际上将接收该文件的android代码。循环开始并且不退出。与端口的连接正确,我可以发送和接收字符串

     public Bitmap receiveFile(InputStream is) throws Exception{
     String baseDir =     Environment.getExternalStorageDirectory().getAbsolutePath();
        String fileName = "myFile.png";
        String imageInSD = baseDir + File.separator + fileName;
      int filesize=6022386;
      int bytesRead;
      int current = 0;
      byte [] mybytearray  = new byte [filesize];

        FileOutputStream fos = new FileOutputStream(imageInSD);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        bytesRead = is.read(mybytearray,0,mybytearray.length);
        current = bytesRead;


        do {
           bytesRead =
              is.read(mybytearray, current, (mybytearray.length-current));
           if(bytesRead >= 0) current += bytesRead;

        } while(bytesRead != -1);

        bos.write(mybytearray, 0 , current);
        bos.flush();
        bos.close();
        return null;
  }


也请提出其他分享图片的方式

最佳答案

这是问题所在:

       if(bytesRead >= 0) current += bytesRead;


当您从TCP套接字接收到0字节时,这意味着另一端已关闭连接,因此不再需要读取其他内容。此时退出循环。

09-16 07:14
查看更多