java斷點續傳
1. java 斷點續傳需要哪些jar包
Java-->實現斷點續傳(下載)
--> 斷點續傳: 就像迅雷下載文件一樣,停止下載或關閉程序,下次下載時是從上次下載的地方開始繼續進行,而不是重頭開始...
--> RandomAccessFile --> pointer(文件指針) --> seek(移動文件指針) --> 斷點續傳
package com.dragon.java.downloadfile;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
/*
斷點續傳:對下載軟體非常重要!
--> 第一次下載 100 位元組
--> 第二次下載 101 位元組...想辦法知道上次從哪個地方斷掉的。 上次已經下載到了什麼位置。 記下斷點的位置
------> 需要第三方的文件專門記住斷點的位置
*/
public class Test {
public static void main(String args[]) {
File srcFile = new File("D:/Java4Android/01_Java考古學/01_Java考古學.mp4");
File desDir = new File("f:/vidio");
FileToDir(srcFile, desDir);
}
public static void FileToDir(File srcFile, File desDir) {
desDir.mkdirs();
// 創建配置文件
File configFile = new File(desDir, srcFile.getName().split("\\.")[0]
+ ".config");
// 創建目標文件
File desFile = new File(desDir, srcFile.getName());
if (!configFile.exists() && desFile.exists()) {
System.out.println("已下載過該文件!");
return;
}
RandomAccessFile rafSrc = null;
RandomAccessFile rafDes = null;
RandomAccessFile rafConfig = null;
try {
rafSrc = new RandomAccessFile(srcFile, "r");
rafDes = new RandomAccessFile(desFile, "rw");
rafConfig = new RandomAccessFile(configFile, "rw");
// 設置目標文件和源文件一樣長
rafDes.setLength(srcFile.length());
// 設置配置的文件長度為8,防止第一次下載是出現EOF 異常
rafConfig.setLength(8);
// 從上次下載的位置開始繼續下載!
long pointer = rafConfig.readLong();
System.out.println("已下載:" + ((float) pointer / srcFile.length())
* 100 + "%");
rafSrc.seek(pointer);
rafDes.seek(pointer);
// 單次傳輸長度設置小點,好觀察是否斷點續傳
byte[] buffer = new byte[32];
int len = -1;
// 每次復制的開始,必須把源文件的指針和目標文件的指針從上次斷開的位置去讀
while ((len = rafSrc.read(buffer)) != -1) {
rafDes.write(buffer, 0, len);
// 在配置文件寫的時候,每次使文件指針移動到最初的位置 --> 這樣永遠對只會存儲前8個位元組
rafConfig.seek(0);
// 每復制一次之和,趕緊記錄下文件指針的位置,以備斷點續傳使用。
rafConfig.writeLong(rafSrc.getFilePointer());
}
} catch (IOException e) {
System.out.println(e);
} finally {
try {
rafSrc.close();
rafDes.close();
rafConfig.close();
} catch (IOException e) {
System.out.println(e);
}
// 在流關閉之後刪除配置文件
System.out.println("下載成功!");
configFile.delete();
}
}
}
2. java socket數據流斷點續傳
設備往你這邊傳輸數據時,你得知他的設備ID、數據的MD5校驗值、操作授權代碼。
傳輸數據開始,設備向你這邊傳輸數據,你這邊將受到的數據保存到文件或者資料庫。傳輸過程中,你可能要告訴設備已經保存的數據位元組數。
假如網路連接異常,按照你說的思路,發送心跳包檢測連接情況。你這邊程序將本次操作的數據保存、並將設備ID、數據MD5校驗值、操作授權碼、已保存的位元組數保存到日誌。
下次客戶端請求續傳,你就校驗它的設備ID、操作授權代碼,然後再告訴它從哪裡開始續傳,跳過那些位元組。
續傳完成,通知客戶端,續傳成功。
3. java ftp怎麼實現java ftp方式的斷點續傳
運用類的辦法,編程人員能夠長途登錄到FTP伺服器,羅列該伺服器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵 蓋了簡直一切FTP的功用,FtpClient的實例變數保留了有關樹立"署理"的各種信息。下面給出了這些實例變數:
public static boolean useFtpProxy
這個變數用於標明FTP傳輸過程中是不是運用了一個署理,因此,它實際上是一個符號,此符號若為TRUE,標明運用了一個署理主機。
public static String ftpProxyHost
此變數只要在變數useFtpProxy為TRUE時才有用,用於保留署理主機名。
public static int ftpProxyPort
此變數只要在變數useFtpProxy為TRUE時才有用,用於保留署理主機的埠地址。
FtpClient有三種不同方式的結構函數,如下所示:
1、public FtpClient(String hostname,int port)
此結構函數運用給出的主機名和埠號樹立一條FTP銜接。
2、public FtpClient(String hostname)
此結構函數運用給出的主機名樹立一條FTP銜接,運用默許埠號。
3、FtpClient()
此結構函數將創立一FtpClient類,但不樹立FTP銜接。這時,FTP銜接能夠用openServer辦法樹立。
一旦樹立了類FtpClient,就能夠用這個類的辦法來翻開與FTP伺服器的銜接。類ftpClient供給了如下兩個可用於翻開與FTP伺服器之間的銜接的辦法。
public void openServer(String hostname)
這個辦法用於樹立一條與指定主機上的FTP伺服器的銜接,運用默許埠號。
4. Java Socket如何實現文件的斷點續傳,有代碼更好
上傳:
上傳時附帶一個描述數據起始位置的參數。
接受的一端接收到數據後,按照起始位置續寫文件。
下載:
按照本地已保存的大小,提交下載請求。
伺服器按照請求的位置,傳數據。
大概就是這么個意思。還要處理很多異常情況。
5. 用java向hdfs上傳文件時,如何實現斷點續傳
@Component("javaLargeFileUploaderServlet")
@WebServlet(name = "javaLargeFileUploaderServlet", urlPatterns = { "/javaLargeFileUploaderServlet" })
public class UploadServlet extends HttpRequestHandlerServlet
implements HttpRequestHandler {
private static final Logger log = LoggerFactory.getLogger(UploadServlet.class);
@Autowired
UploadProcessor uploadProcessor;
@Autowired
FileUploaderHelper fileUploaderHelper;
@Autowired
ExceptionCodeMappingHelper exceptionCodeMappingHelper;
@Autowired
Authorizer authorizer;
@Autowired
StaticStateIdentifierManager staticStateIdentifierManager;
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws IOException {
log.trace("Handling request");
Serializable jsonObject = null;
try {
// extract the action from the request
UploadServletAction actionByParameterName =
UploadServletAction.valueOf(fileUploaderHelper.getParameterValue(request, UploadServletParameter.action));
// check authorization
checkAuthorization(request, actionByParameterName);
// then process the asked action
jsonObject = processAction(actionByParameterName, request);
// if something has to be written to the response
if (jsonObject != null) {
fileUploaderHelper.writeToResponse(jsonObject, response);
}
}
// If exception, write it
catch (Exception e) {
exceptionCodeMappingHelper.processException(e, response);
}
}
private void checkAuthorization(HttpServletRequest request, UploadServletAction actionByParameterName)
throws MissingParameterException, AuthorizationException {
// check authorization
// if its not get progress (because we do not really care about authorization for get
// progress and it uses an array of file ids)
if (!actionByParameterName.equals(UploadServletAction.getProgress)) {
// extract uuid
final String fileIdFieldValue = fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId, false);
// if this is init, the identifier is the one in parameter
UUID clientOrJobId;
String parameter = fileUploaderHelper.getParameterValue(request, UploadServletParameter.clientId, false);
if (actionByParameterName.equals(UploadServletAction.getConfig) && parameter != null) {
clientOrJobId = UUID.fromString(parameter);
}
// if not, get it from manager
else {
clientOrJobId = staticStateIdentifierManager.getIdentifier();
}
// call authorizer
authorizer.getAuthorization(
request,
actionByParameterName,
clientOrJobId,
fileIdFieldValue != null ? getFileIdsFromString(fileIdFieldValue).toArray(new UUID[] {}) : null);
}
}
private Serializable processAction(UploadServletAction actionByParameterName, HttpServletRequest request)
throws Exception {
log.debug("Processing action " + actionByParameterName.name());
Serializable returnObject = null;
switch (actionByParameterName) {
case getConfig:
String parameterValue = fileUploaderHelper.getParameterValue(request, UploadServletParameter.clientId, false);
returnObject =
uploadProcessor.getConfig(
parameterValue != null ? UUID.fromString(parameterValue) : null);
break;
case verifyCrcOfUncheckedPart:
returnObject = verifyCrcOfUncheckedPart(request);
break;
case prepareUpload:
returnObject = prepareUpload(request);
break;
case clearFile:
uploadProcessor.clearFile(UUID.fromString(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId)));
break;
case clearAll:
uploadProcessor.clearAll();
break;
case pauseFile:
List<UUID> uuids = getFileIdsFromString(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId));
uploadProcessor.pauseFile(uuids);
break;
case resumeFile:
returnObject =
uploadProcessor.resumeFile(UUID.fromString(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId)));
break;
case setRate:
uploadProcessor.setUploadRate(UUID.fromString(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId)),
Long.valueOf(fileUploaderHelper.getParameterValue(request, UploadServletParameter.rate)));
break;
case getProgress:
returnObject = getProgress(request);
break;
}
return returnObject;
}
List<UUID> getFileIdsFromString(String fileIds) {
String[] splittedFileIds = fileIds.split(",");
List<UUID> uuids = Lists.newArrayList();
for (int i = 0; i < splittedFileIds.length; i++) {
uuids.add(UUID.fromString(splittedFileIds[i]));
}
return uuids;
}
private Serializable getProgress(HttpServletRequest request)
throws MissingParameterException {
Serializable returnObject;
String[] ids =
new Gson()
.fromJson(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId), String[].class);
Collection<UUID> uuids = Collections2.transform(Arrays.asList(ids), new Function<String, UUID>() {
@Override
public UUID apply(String input) {
return UUID.fromString(input);
}
});
returnObject = Maps.newHashMap();
for (UUID fileId : uuids) {
try {
ProgressJson progress = uploadProcessor.getProgress(fileId);
((HashMap<String, ProgressJson>) returnObject).put(fileId.toString(), progress);
}
catch (FileNotFoundException e) {
log.debug("No progress will be retrieved for " + fileId + " because " + e.getMessage());
}
}
return returnObject;
}
private Serializable prepareUpload(HttpServletRequest request)
throws MissingParameterException, IOException {
// extract file information
PrepareUploadJson[] fromJson =
new Gson()
.fromJson(fileUploaderHelper.getParameterValue(request, UploadServletParameter.newFiles), PrepareUploadJson[].class);
// prepare them
final HashMap<String, UUID> prepareUpload = uploadProcessor.prepareUpload(fromJson);
// return them
return Maps.newHashMap(Maps.transformValues(prepareUpload, new Function<UUID, String>() {
public String apply(UUID input) {
return input.toString();
};
}));
}
private Boolean verifyCrcOfUncheckedPart(HttpServletRequest request)
throws IOException, MissingParameterException, FileCorruptedException, FileStillProcessingException {
UUID fileId = UUID.fromString(fileUploaderHelper.getParameterValue(request, UploadServletParameter.fileId));
try {
uploadProcessor.verifyCrcOfUncheckedPart(fileId,
fileUploaderHelper.getParameterValue(request, UploadServletParameter.crc));
}
catch (InvalidCrcException e) {
// no need to log this exception, a fallback behaviour is defined in the
// throwing method.
// but we need to return something!
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}
6. Java Socket如何實現文件的斷點續傳,有代碼更好
1package com.tangshun.www.socket;
2
3import java.io.File;
4import java.io.IOException;
5import java.io.InputStream;
6import java.io.RandomAccessFile;
7import java.net.HttpURLConnection;
8import java.net.MalformedURLException;
9import java.net.URL;
10
11//斷點續傳
12public class DownLoad {
13
14 public static void down(String URL, long nPos, String savePathAndFile) {
15 try {
16 URL url = new URL(URL);
17 HttpURLConnection httpConnection = (HttpURLConnection) url
18 .openConnection();
19 // 設置User-Agent
20 httpConnection.setRequestProperty("User-Agent", "NetFox");
21 // 設置斷點續傳的開始位置
22 httpConnection.setRequestProperty("RANGE", "bytes=" + nPos);
23 // 獲得輸入流
24 InputStream input = httpConnection.getInputStream();
25 RandomAccessFile oSavedFile = new RandomAccessFile(savePathAndFile,
26 "rw");
27 // 定位文件指針到nPos位置
28 oSavedFile.seek(nPos);
29 byte[] b = new byte[1024];
30 int nRead;
31 // 從輸入流中讀入位元組流,然後寫到文件中
32 while ((nRead = input.read(b, 0, 1024)) > 0) {
33 (oSavedFile).write(b, 0, nRead);
34 }
35 httpConnection.disconnect();
36 } catch (MalformedURLException e) {
37 e.printStackTrace();
38 } catch (IOException e) {
39 e.printStackTrace();
40 }
41 }
42
43 public static long getRemoteFileSize(String url) {
44 long size = 0;
45 try {
46 HttpURLConnection conn = (HttpURLConnection) (new URL(url))
47 .openConnection();
48 size = conn.getContentLength();
49 conn.disconnect();
50 } catch (Exception e) {
51 e.printStackTrace();
52 }
53 return size;
54 }
55
56public static void main(String[] args) {
57 String url = " http://www.videosource.cgogo.com/media/0/16/8678/8678.flv";
58 String savePath = "F:\\";
59 String fileName = url.substring(url.lastIndexOf("/"));
60 String fileNam=fileName;
61 HttpURLConnection conn = null;
62 try {
63 conn = (HttpURLConnection) (new URL(url)).openConnection();
64 } catch (Exception e) {
65 e.printStackTrace();
66 }
67 File file = new File(savePath + fileName);
68 // 獲得遠程文件大小
69 long remoteFileSize = getRemoteFileSize(url);
70 System.out.println("遠程文件大小="+remoteFileSize);
71 int i = 0;
72 if (file.exists()) {
73 // 先看看是否是完整的,完整,換名字,跳出循環,不完整,繼續下載
74 long localFileSize = file.length();
75 System.out.println("已有文件大小為:"+localFileSize);
76
77 if (localFileSize < remoteFileSize) {
78 System.out.println("文件續傳");
79 down(url, localFileSize, savePath + fileName);
80 }else{
81 System.out.println("文件存在,重新下載");
82 do{
83 i++;
84 fileName = fileNam.substring(0, fileNam.indexOf(".")) + "(" + i
85 + ")" + fileNam.substring(fileNam.indexOf("."));
86
87 file = new File(savePath + fileName);
88 }while(file.exists());
89 try {
90 file.createNewFile();
91 } catch (IOException e) {
92 e.printStackTrace();
93 }
94 down(url, 0, savePath + fileName);
95 }
96 // 下面表示文件存在,改名字
97
98 } else {
99 try {
100 file.createNewFile();
101 System.out.println("下載中");
102 down(url, 0, savePath + fileName);
103 } catch (IOException e) {
104 e.printStackTrace();
105 }
106 }
107 }}
108
7. java不用RandomAccessFile如何實現斷點續傳
斷點續傳不一定要RandomAccessFile,只要接收端告訴發送端已經接受到什麼位置了,那麼發送端就可以從這個位置開始往後讀~然後讀出來的數據給發送端就行了~
8. java實現ftp斷點續傳問題
//嘗試移動文件內讀取指針,實現斷點續傳
result
=
uploadFile(remoteFileName,
f,
ftpClient,
remoteSize);
//如果斷點續傳沒有成功,則刪除伺服器上文件,重新上傳
if(result
==
UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
return
UploadStatus.Delete_Remote_Faild;
}
result
=
uploadFile(remoteFileName,
f,
ftpClient,
0);
}
9. 關於JAVA斷點續傳
024位元組)。第一次B接收了512位元組,那麼第二次連接A就應該從513位元組開始傳輸。
也就是說,在第二次傳輸時,B要提供「我要從513位元組開始傳送文件F」的信息,然後A使用FileInputStream構建輸入流讀取本地文件,使用skip(512)方法跳過文件F的前512位元組再傳送文件,之後B將數據追加(append)到先前接收的文件末尾即可。
進一步考慮,如果要實現多線程傳送,即分塊傳輸,也同樣的道理。假如B要求分作兩塊同時傳輸,那麼A啟動兩個線程,一個從513位元組讀到768位元組(工256位元組),第二個線程從769位元組到1024位元組即可。
如果你要從網路上下載文件,就是說A方不是你實現的,那麼你要先確認A方支不支持斷電續傳功能(HTTP1.1),然後你查閱下HTTP1.1協議,在HTTP1.1版本里,可以通過設置請求包頭某個欄位的信息(使用URLConnection創建連接並使用setRequestProperty(String key, String value) 方法設置)從而精確讀取文件的某一段數據的。注意,基於HTTP斷點續傳的關鍵是1.1版本,1.0版本是不支持的。
補充:
嗯,查到了,是設置range屬性,即setRequestProperty("range", "bytes=513-1024").你可以使用迅雷下載某個文件,然後從」線程信息「中就可以看到這個http1.1斷點續傳的所有行為信息了。
10. java web斷點續傳,我用的是fileupload來做的上傳。
使用Struts2上傳文件:
Struts文件上傳需要使用File Upload Filter。Filter Upload Filter使用一些默認的規則:
Form中的<s:file name="image"></s:file>標簽對應著Action類中的三個屬性分別是:上傳文件(java.io.File類型),文件名(java.lang.String類型),文件類型(java.lang.String類型,例如:image/jpeg)。命名規約為:
文件:名字與<s:file>標簽中的name屬性一致,這里為:image
文件名:文件 + FileName,這里為:imageFileName
文件類型:文件 + ContentType,這里為:imageContentType
所以針對上述<s:file name="image"></s:file>表示啊的上傳文件的JSP和Action類被別為:
imageUpload.jsp:
[html]view plain
<%@pagecontentType="text/html;charset=UTF-8"language="java"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<html>
<head><title>ImageUpload</title></head>
<body>
<h1>ImageUploadPage</h1>
<s:formaction="imageUpload"method="post"enctype="multipart/form-data">
<s:filename="image"></s:file>
<s:submit></s:submit>
</s:form>
</body>
</html>
packagecom.jpleasure;
importcom.opensymphony.xwork2.ActionSupport;
importjava.io.File;
importjava.io.InputStream;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
{
privateFileimage;
privateStringimageFileName;
privateStringimageContentType;
publicFilegetImage(){
returnimage;
}
publicvoidsetImage(Fileimage){
this.image=image;
}
publicStringgetImageFileName(){
returnimageFileName;
}
publicvoidsetImageFileName(StringimageFileName){
this.imageFileName=imageFileName;
}
(){
returnimageContentType;
}
publicvoidsetImageContentType(StringimageContentType){
this.imageContentType=imageContentType;
}
publicStringexecute(){
if(image!=null){
System.out.println("filenameis:"+this.imageFileName);
System.out.println("filecontenttypeis:"+this.imageContentType);
System.out.println("filelengthis:"+this.image.length());
}
returnSUCCESS;
}
}
<actionname="imageUpload"class="com.jpleasure.ImageUploadAction">
<result>/success.jsp</result>
</action>
packagecom.jpleasure;
importcom.opensymphony.xwork2.ActionSupport;
importjava.io.File;
importjava.io.InputStream;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
{
privateFileimage;
privateStringimageFileName;
privateStringimageContentType;
=null;
(){
returnimageInputStream;
}
publicvoidsetImageInputStream(InputStreamimageInputStream){
this.imageInputStream=imageInputStream;
}
publicFilegetImage(){
returnimage;
}
publicvoidsetImage(Fileimage){
this.image=image;
}
publicStringgetImageFileName(){
returnimageFileName;
}
publicvoidsetImageFileName(StringimageFileName){
this.imageFileName=imageFileName;
}
(){
returnimageContentType;
}
publicvoidsetImageContentType(StringimageContentType){
this.imageContentType=imageContentType;
}
publicStringexecute(){
if(image!=null){
System.out.println("filenameis:"+this.imageFileName);
System.out.println("filecontenttypeis:"+this.imageContentType);
System.out.println("filelengthis:"+this.image.length());
try{
this.imageInputStream=newFileInputStream(image);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
}
returnSUCCESS;
}
}
<actionname="imageUpload"class="com.jpleasure.ImageUploadAction">
<resultname="success"type="stream">
<paramname="contentType">image/pjpeg</param>
<paramname="inputName">imageInputStream</param>
<paramname="contentDisposition">attachment;filename="image.jpg"</param>
<paramname="bufferSize">1024</param>
</result>
</action>
<struts>
<packagename="myPackage"extends="struts-default">
<interceptor-refname="fileUpload">
<paramname="maximumSize">2MB</param>
<paramname="allowedTypes">text/html,image/jpeg</param>
</interceptor-ref>
<interceptor-refname="basicStack"/>
<actionname="imageUpload"class="com.jpleasure.ImageUploadAction">
<resultname="success"type="stream">
<paramname="contentType">image/pjpeg</param>
<paramname="inputName">imageInputStream</param>
<paramname="contentDisposition">
attachment;filename="image.jpg"
</param>
<paramname="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
ImageUploadAction.java:
[html]view plain
Struts.xml配置文件:
[html]view plain
這樣當我們選中上傳文件,提交的時候:文件內容會以File類型的方式放在image聲明的變數中。文件的名字將會被放在imageFileName命名的變數中,文件的類型被放在imageContentType命名的變數中。
文件下載:
文件下載需要使用一個特殊的Result,stream類型的Result。Stream類型的Result主要用來處理文件下載操作。
處理原理為:所有的下載文件都是將一個二進制的流寫入到HttpResponse中去。在Action類中定義一個InputSream類型的二進制流,在Result返回給用戶的時候返回給用戶。
擴展上述的代碼,將上傳來的文件直接下載給用戶:
ImageUploadAction中需要追加一個InputSream類型的對象,並且指向上傳的文件,代碼如下,紅色部分表示變化:
[html]view plain
配置文件為,紅色為變化部分:
[html]view plain
ContentType表示下載文件的類型。
InputName表示Action類中用來下載文件的欄位的名字。
ContentDisposition用來控制文件下載的一些信息,包括是否打開另存對話框,下載文件名等。
BufferSize表示文件下載時使用的緩沖區的大小。
實際項目開發的考慮:
控制上傳文件的類型和最大允許上傳文件的size
使用File Upload Intercepter的參數可盈控制上傳文件的類型和最大允許上傳文件的size。例如:
[html]view plain
上述表示允許上傳jpeg和html類型的文件,且最大文件上傳size為2MB
顯示錯誤信息:
可以使用如下key表示的message來顯示文件上傳出錯的提示信息:
消息Key 說明
struts.messages.error.uploading 文件無法正常上傳時的公共錯誤
struts.messages.error.file.too.large 文件大小超過最大允許size時的錯誤提示
struts.messages.error.content.type.not.allowed 文件類型不在上傳文件允許類型中的錯誤提示