0

在我的应用程序中,我将一个 byte[](序列化对象)上传到我的 FTP 服务器,它运行良好。但是,当我尝试下载它时,只有数组的第一部分(如 3000 字节)是正确的,其余部分用零填充。

我似乎无法弄清楚出了什么问题,任何帮助将不胜感激。我正在使用包 org.apache.commons.net.*

public static byte[] downloadBoard( String host, int port, String usr, String pwd) throws IOException {
  FTPClient ftpClient = new FTPClient();
  byte[] buf = new byte[20000];

  try {
    ftpClient.connect( host, port );
    ftpClient.login( usr, pwd );

    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    InputStream is = ftpClient.retrieveFileStream("asdf.board");
    is.read(buf);
    is.close();

    ftpClient.completePendingCommand();
    ftpClient.logout();
  } finally {
    ftpClient.disconnect();
  }
  return buf;
}
4

2 回答 2

2

InputStream.read()通常不会为您读取整个流,而只会读取其中的一部分。请注意,InputStream.read()返回实际读取的字节数,您需要对其进行检查。

典型的模式是循环直到InputStream报告没有更多字节可用。

于 2012-06-18T22:26:02.193 回答
2

is.read() 可能不会返回完整内容。您需要将 read() 放入类似于此的循环中:

int pos = 0;
while (true) {
  int count = is.read(buf, pos, buf.length - pos);
  if (count <= 0) {
    break;
  }
  pos += count;
}

PS:

如果您知道文件的大小,则可以使用 DataInputStream 读取缓冲区而无需循环:

byte[] buf = new byte[exactFileSize];
DataInputStream dis = new DataInputStream(is);
dis.readFully(buf);
于 2012-06-18T22:28:56.000 回答