我正在编程一个服务器客户端应用程序,并且在将来自服务器的二进制字节数组转换为设备时遇到问题。套接字通信问题[Android]
我用的代码是下一个:当歌曲已经下载
int bytesRead = 0;
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dosToFile = new DataOutputStream(fos);
long totalBytesWritten = 0;
byte[] buffer = new byte[5024];
do {
bytesRead = dis.read(buffer, 0, 5024);
if (bytesRead > 0) {
dosToFile.write(buffer, 0, bytesRead);
dosToFile.flush();
totalBytesWritten += bytesRead;
Log.e("", "Total Bytes written = "+ totalBytesWritten);
} else if (bytesRead == 0) {
Log.e("","Zero bytes readed when downloading song.");
} else if (bytesRead == -1) {
Log.e("","Read returned -1 when downloading song.");
}
} while (bytesRead > -1);
的问题就来了。在最后一次读取中,在读完歌曲的最后几个字节(并将它们写入SD卡)之后,应用程序在读取中冻结,并且不会返回假设的-1。
代码显示错误?我应该以其他方式转移吗?
我把我的二进制数据,此代码:
byte [] mybytearray = new byte [(int)myFile.length()];
mybytearray = this.fileToByteArray(myFile);
if (mybytearray != null) {
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
System.out.println("Song send.");
} else {
System.out.println("The song could not be send.");
}
非常感谢你。
你好,杰克。它仍然在最后一次读取时被阻塞。我编辑了我的第一篇文章,向您展示如何从服务器发送数据。谢谢 – newlog
最后,我解决了这个问题,将写入的字节与文件的总长度进行比较,如果它们相等则打破循环。 – newlog