关于java的ftp中发送数据和接收数据流的问题

卡卡1314 2009-10-08 10:51:24
在发送端发送数据:
DataOutputStream outputs=null;
RandomAccessFile sendFile=null;
TelnetOutputStream outs=null;
byte[] b = new byte[2048000];
sendFile=new RandomAccessFile(FtpVariable.RWFileDir+file,"r");
sendFile.seek(0);

//调用上传文件的命令
outs=ftpClient.put(file);

//打开一个输出流
outputs=new DataOutputStream(outs);

while((sendFile.getFilePointer())<sendFile.length())
{
if(sendFile.length()-sendFile.getFilePointer()>=FtpVariable.dataPacketSize)
{
sendFile.read(b);//从文件中读出数据
outputs.write(b);//把数据写入输出流
}
else
{

sendFile.read(b,0,(int)(sendFile.length()-sendFile.getFilePointer()));
outputs.write(b);
}
}
在接收端接收数据:
BufferedOutputStream fout=null;
BufferedInputStream din=null;
byte[] buf = new byte[2048000];
fout= new BufferedOutputStream(new FileOutputStream(requestfile));
din = new BufferedInputStream(dsocket.getInputStream());
while((dataLength = din.read(buf,0,buf.length))!=-1)
{
fout.write(buf,0,dataLength);//写入文件
}


我上传一个6MB的可以正常接收到。但是上传一个5.688mb时,也是接收到6mb,上传1.969mb是,接收到的是2mb,上传3.571mb时,接收到的是4mb。
把byte[] buf = new byte[2048000];改为byte[] buf = new byte[8192000];
上传3.571mb时,接收到的是8mb;上传1.969mb时,接收到的也是8mb;上传6mb时,接收到的也是8mb。


请各位高手帮帮忙,我找了很久都没有找出原因。
...全文
257 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
swandragon 2009-10-09
  • 打赏
  • 举报
回复
while((dataLength = din.read(buf))!=-1)
{
fout.write(buf,0,dataLength);//写入文件
}
这样试试
卡卡1314 2009-10-09
  • 打赏
  • 举报
回复
真的很谢谢你们,
用while((dataLength = din.read(buf))!=-1)
{
fout.write(buf,0,dataLength);//写入文件
}
可以实现。
卡卡1314 2009-10-08
  • 打赏
  • 举报
回复
在发送端我试过把read到的长度相加和文件的大小是没有增加的,但是在接收端取的话,就增加了。
swandragon 2009-10-08
  • 打赏
  • 举报
回复
可能是发送的时候发送多了

int k = 0;
while((sendFile.getFilePointer()) <sendFile.length())
{
if(sendFile.length()-sendFile.getFilePointer()>=FtpVariable.dataPacketSize)
{
k = sendFile.read(b);//从文件中读出数据
outputs.write(b,0,k);//把数据写入输出流
}
else
{

k = sendFile.read(b,0,(int)(sendFile.length()-sendFile.getFilePointer()));
outputs.write(b,0,k);
}
}
loveofmylife 2009-10-08
  • 打赏
  • 举报
回复
以前写的一个传文件的,你可以参考一下
发送:
DataOutputStream dos=null;
FileInputStream fis=null;
try {
dos=new DataOutputStream(s.getOutputStream());
fis=new FileInputStream(file);
byte[] buf=new byte[2048];
int num=0;
while((num=fis.read(buf))!=(-1))
{//是否读完所有数据
dos.write(buf,0,num);//将数据写往文件
dos.flush();
}

接受:
JFileChooser jfc=new JFileChooser();
jfc.setSelectedFile(new File(jfc.getCurrentDirectory().getAbsolutePath(),name));
jfc.showSaveDialog(frame);
File f=jfc.getSelectedFile();
f.createNewFile();
dis=new DataInputStream(scoket.getInputStream());
RandomAccessFile raf=new RandomAccessFile(f,"rw");
byte[] buf=new byte[2048];
int num=0;
while((num=dis.read(buf))!=(-1))
{
raf.write(buf,0,num);
raf.skipBytes(num);
}
br.close();
dis.close();
raf.close();
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧