【问题标题】:I am sending picture file from pc to android phone both are connected to same WLAN via socket我正在将图片文件从 pc 发送到 android 手机两者都通过套接字连接到同一个 WLAN
【发布时间】:2012-12-05 19:21:30
【问题描述】:

我正在尝试将图片从 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;
  }

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

【问题讨论】:

    标签: java android sockets network-programming


    【解决方案1】:

    这一行是问题:

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

    当您从 TCP 套接字接收到 0 字节时,这意味着另一端已关闭连接,因此没有更多内容可读取。此时退出循环。

    【讨论】:

    • 因为我不确定您的实际意思以及您建议的更改类型
    • 添加显式检查 bytesRead 是否为零并退出循环。
    • if (is.available()==0) 中断;我在上面使用检查它工作正常并读取所有字节但文件被裁剪
    猜你喜欢
    • 2020-07-17
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    相关资源
    最近更新 更多