【发布时间】:2015-11-10 21:45:43
【问题描述】:
我正在尝试将一些文件从服务器发送到 android 中的一些客户端。 我通过 read(byte[] array,int startIndex,int arraySize) 方法通过 bufferedInputStream 接收文件,该方法返回它可以读取的字节数,如果没有要读取的输入,则返回 -1。 我在循环中接收文件,当我的文件完成时我必须退出循环,但是读取方法不返回-1,只是等待更多输入来读取:/ 所以我的代码被阻塞了...... 我试图从服务器发送文件大小,并在接收它时,每次读取缓冲区时都会从中减去读取字节的数字,所以当这个数字达到 0 时意味着我收到了所有文件并且应该打破循环,但在某些文件中它没有达到 0,就好像我的文件的某些部分没有发送一样:|但是当我在服务器端做同样的事情时(从早期文件大小中减去发送的部分)它总是命中 0 .... 所以我的问题是如何知道我阅读了所有文件以打破阅读循环:( similar question 我的问题与此链接不同,因为我完成了建议的答案,但某些文件中剩余的文件大小未达到 0,我不知道为什么
这是我在服务器端发送文件的代码:
public void sendFile(File file){
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(outputStream);
byte[] temp = new byte[2 * 1024];
int length ;
int fileSize=(int)file.length();
Log.d("file size",Integer.toString(fileSize));
//int sendSize =0;
while (true){
length = bis.read(temp,0,temp.length);
if(length == -1) break;
bos.write(temp,0,length);
fileSize-=length;
assert (fileSize >=0 );
//if(fileSize==0)break;
}
// outputStream.write(-1);
bos.flush();
Log.d("File ", "Send finisheeed!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}finally {
try {
bis.close();
//bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是接收文件的客户端代码部分:
Log.d("File name is", fileName);
// File outFile = new File("/storage/sdcard0/m2app" + fileName);
// outFile.createNewFile();
bos = new BufferedOutputStream(new FileOutputStream("/storage/sdcard0/m2app" + fileName));
byte[] temp = new byte[2 * 1024];
int length = 0;
while (true)
{
length = bis.read(temp,0,temp.length);
fileLength -= length;
// Log.d("read",Integer.toString(fileLength) );
if(length == -1 || fileLength == 0 ) {
// if(temp[length-1] == -1){
// bos.write(temp,0,length-1);
// bos.flush();
// Log.d("file","recived!!!!!!!!!!");
break;
}
if(fileLength < 4000 && bis.available() == 0)
break;
bos.write(temp,0,length);
bos.flush();
/*if(fileLength == 0){
Log.d("file","0 shod");
break;
}*/
}
while (fileLength > 0 )
fileLength-=bis.skip(fileLength);
// inputStream.reset();
bos.close();
Log.d("File " , "Receiving finisheeeeeeeeeddddd!!!");
isFile = false;
【问题讨论】:
-
@ejp 我的问题没有重复,我解释了原因...请删除您的重复标签:(
-
上面的代码中没有任何类似于建议的答案。
标签: java android sockets stream