在后台项目中经常会要求有下载和上传功能的实现,在大文件传输的过程中可以实现断点传输避免重复下载:现在我们来整理一下,也可以作为一个项目的亮点。
由于是本地测试,所以是将"D:/test/remote/file.txt"传送到"D:/test/local/file.txt",如果是使用FTP传送,使用FtpClient就可以了。
1 单线程读取
为方便整理逻辑,先使用单线程完成对需求的实现。
关键: RandomAccessFile 可以实现任意位置开始读取/写入
File f=new File(“D:/test.txt”);
RandomAccessFile localFile = new RandomAccessFile(f,“rw”);
localFile.seek(position);
localFile.write(buf);
code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import com.springboot.SpringBootHello.service.FtpDownLoadService;
import com.springboot.SpringBootUtill.downLoadThread;
public class FtpDownLoadServiceImply implements FtpDownLoadService{
@Override
public void downLoadSingleFile(File loacalFile, String remoteFilePath) {
// TODO Auto-generated method stub
File remoteFile=new File(remoteFilePath);
checkFile(loacalFile); //查看本地文件是否存在不存在则创建
long localSize=loacalFile.length();
long remoteSize=remoteFile.length();
long step=localSize;//本地文件的大小作为标记的position;
if (localSize<remoteSize &&