62,615
社区成员
发帖
与我相关
我的任务
分享
public class FileUploadTask {
public static void main(String[] args) {
String fromPath = "d:\\targetFile.avi";
String tmpPath = "e:\\temp\\";
FileUploadTask fileTask = new FileUploadTask();
long s = System.currentTimeMillis();
fileTask.uploadFileByPoint(fromPath, tmpPath);
long e = System.currentTimeMillis();
System.out.println("all cost time :" + (e - s) + " ms");
}
/**
* upload file by point
*
* @param targetPath
* @param uploadPath
*/
public void uploadFileByPoint(String targetPath, String uploadPath) {
File targetFile = new File(targetPath);
String fileName = targetFile.getName();
int nlastPoint = fileName.lastIndexOf(".");
String prefix = fileName.substring(0, nlastPoint);
String suffix = fileName.substring(nlastPoint);
File uploadFile = new File(uploadPath + fileName);
File tmpFile = new File(uploadPath + prefix + ".dat");
// if upload file exist,rename upload file
if (uploadFile.exists()) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
Date date = new Date();
uploadFile.renameTo(new File(uploadPath + prefix + "_["
+ sdf.format(date) + "]" + suffix));
}
long lfBytes = targetFile.length();
long ltmpfBytes = tmpFile.length();
System.out.println("target file size:" + lfBytes + " bytes");
System.out.println("temp file size:" + ltmpfBytes + " bytes");
FileInputStream fileIn = null;
BufferedInputStream bufIn = null;
RandomAccessFile randomFile = null;
try {
fileIn = new FileInputStream(targetFile);
bufIn = new BufferedInputStream(fileIn);
randomFile = new RandomAccessFile(tmpFile, "rw");
// skip the temp file bytes
bufIn.skip(ltmpfBytes);
// offset file point bytes
randomFile.seek(ltmpfBytes);
byte[] bytes = new byte[1024];
while (bufIn.read(bytes) != -1) {
randomFile.write(bytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// release memory to free
releaseMemory(fileIn, bufIn, randomFile);
// upload file over,remark file size
ltmpfBytes = tmpFile.length();
System.out
.println("upload file over size:" + ltmpfBytes + " bytes");
// if upload over,rename the temp file
if (ltmpfBytes >= lfBytes) {
tmpFile.renameTo(new File(uploadPath + fileName));
}
}
}
/**
* release memory to free
*
* @param fileIn
* @param bufIn
* @param randomFile
*/
private void releaseMemory(FileInputStream fileIn,
BufferedInputStream bufIn, RandomAccessFile randomFile) {
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bufIn != null) {
try {
bufIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}