读书人

流文件读写有关问题求解答

发布时间: 2013-04-12 18:33:11 作者: rapoo

流文件读写问题,求解答


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();


}
}




这是公司前辈的一段代码,handlePack()返回的是一段byte数组信息,offset指的是偏移量,
length=bis.read(data);
输入流读到的不一定是文件的全部,
 os.write(buffer,0,temp.length+length);
当数组拷贝的时候,不一定把全部的字节用输出流输出。所以需要
 while((length=bis.read(buffer))!=-1)                                                                                                                                            
{
os.write(buffer, 0, length);
}
这段代码,把没有读完的文件的字节用输出流输出




我的问题是输出流中的write(byte[] b,int off,int len),将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。
 while((length=bis.read(buffer))!=-1)                                                                                                                                             


{
os.write(buffer, 0, length);
}

那么这段岂不是读的不是完整的文件,因为
 System.arraycopy(data,0,buffer,temp.length,length); 
只有这么多字节
length=bis.read(buffer))
在buffer中


但实际上输出量最后输出的是完整的字节,是不是第一次os.write没有flush,导致了下面的边读边写可以接着buffer数组的后面进行字节的输出的操作?
希望我能表达清楚我的意思


[解决办法]
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);
}
=======================================
这一步应该是发送给对方的一个确认信息,并没有发送整个文件的意思。
如果没有设置偏移数据,需要发送temp+文件头部的一段数据。最长为1024,读出来的时候,减去了temp长度。
即:没有偏移设置的时候,第一个1024个数据,包含了temp数据。

读书人网 >J2SE开发

热点推荐