繁体   English   中英

我正在将图片文件从PC发送到Android手机,两者都通过套接字连接到同一WLAN

[英]I am sending picture file from pc to android phone both are connected to same WLAN via socket

我正在尝试将图片从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个字节时,这意味着另一端已关闭连接,因此无需再读取其他内容。 此时退出循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM