【发布时间】:2011-08-03 19:05:34
【问题描述】:
我正在编写服务器-客户端应用程序,但在将歌曲作为二进制字节数组从服务器传输到设备时遇到问题。
我使用的代码是下一个:
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 );
当歌曲已经下载时,问题就来了。在最后一次读取中,在读取歌曲的最后一个字节(并将它们写入 sdcard)之后,应用程序在读取中冻结并且它不返回假定的 -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.");
}
非常感谢。
【问题讨论】:
标签: android sockets download communication