流文件读写问题,求解答
int buffsize=1024;
FileInputStream fis= null;
BufferedInputStream bis = null;
try
{
synchronized (socket.getOutputStream())
{
OutputStream os=socket.getOutputStream();
byte [] temp=pack.handlePack(socket);
if(ackcode!=0)
{
os.write(temp);
os.flush();
return;
}
byte [] buffer=new byte[buffsize];
fis=new FileInputStream(file);
System.out.println("offset:" + offset);
fis.skip(offset);
bis=new BufferedInputStream(fis);
int length;
if(offset==0)
{
byte []data=new byte [buffsize-temp.length];
length=bis.read(data);
System.arraycopy(temp,0,buffer,0,temp.length);
System.arraycopy(data,0,buffer,temp.length,length);
os.write(buffer,0,temp.length+length);
}
length=0;
while((length=bis.read(buffer))!=-1)
{
os.write(buffer, 0, length);
}
os.flush();
}
}
length=bis.read(data);输入流读到的不一定是文件的全部,
os.write(buffer,0,temp.length+length);当数组拷贝的时候,不一定把全部的字节用输出流输出。所以需要
while((length=bis.read(buffer))!=-1)这段代码,把没有读完的文件的字节用输出流输出
{
os.write(buffer, 0, length);
}
while((length=bis.read(buffer))!=-1)那么这段岂不是读的不是完整的文件,因为
{
os.write(buffer, 0, length);
}
System.arraycopy(data,0,buffer,temp.length,length);只有这么多字节
length=bis.read(buffer))在buffer中