Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use FTP in Android to realize the function of multithreaded breakpoint continuation, download and upload

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the Android how to use FTP to achieve multi-thread breakpoint download upload function related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that you read this Android how to use FTP to achieve multi-thread breakpoint download upload function article will have a harvest, let's take a look at it.

Principle of FTP download

FTP single-thread breakpoint continuation

FTP is different from the traditional HTTP protocol, because FTP does not have a so-called header file, so we cannot specify a download zone to the server by setting header, as HTTP does.

But the FTP protocol provides a better command REST to recover tasks from a specified location, and the FTP protocol also provides a command SIZE to get the size of downloaded files. With these two commands, there is no problem with FTP breakpoint continuation.

The principle of FTP breakpoint continuation is similar to that of HTTP. When the file is paused, the stop location of the file is recorded. When downloading again, the location of the record is read first. If the location exists, tell the server to download from the specified area through the REST command.

FTP multithreaded breakpoint continuation

The principle of multithreaded download is similar to that of HTTP multithreaded download. First get the file size, and then download the whole file in segments according to the number of threads. When the task stops, record the pause position of each thread, restart the download, and each thread reads the corresponding download record. Then each thread starts downloading from the specified location.

Segmented download

Unlike HTTP, FTP does not provide an API of the file range, so in a segmented download, FTP has only the start position and no end position.

Therefore, you need to stop the thread manually at the specified location.

Function realization

In this paper, we will use apache commons-net to implement the download / upload function of FTP breakpoint continuation.

Through the following steps, you can easily implement FTP breakpoint continuation.

Log in

The FTP protocol is different from the HTTP protocol. When you download using FTP, you need to log in.

Of course, if your server does not have the login function, you can ignore the login operation.

FTPClient client = new FTPClient (); client.connect (serverIp, port); / / Connect to FTP server client.login (userName, passsword)

With the above three lines of code, you can easily log in to the FTP server.

After logging in, you also need to verify that the login was successful

Int reply = client.getReplyCode (); if (! FTPReply.isPositiveCompletion (reply)) {client.disconnect (); Log.d (TAG, "unable to connect to the ftp server, error code:" + reply); return;}

Because there are multiple states of successful connection in the FTP protocol, it needs to be used to verify a successful connection to the FTP server through FTPReply.isPositiveCompletion (reply).

File information acquisition

After connecting to the FTP server, you need to start getting the most important parameters for the download (file length, file name).

The client can obtain a list of files for that path on the FTP server through client.listFiles (remotePath).

If the path is a file, only an array of length 1 is returned.

If the path is a folder, all corresponding files under that folder are returned.

String remotePath = "/ upload/qjnn.apk"; / / File path on the FTP server FTPFile [] files = client.listFiles (remotePath); FTPFile file = files [0]; / / File Information long size = file.getSize (); String fileaName = file.getName ()

If your file is in English and there is no Chinese in the path, you can get the correct file information through the above code.

But if the file name on the server on FTP is in Chinese or the path is in Chinese, then the above code, you will not get the correct file information.

The correct way to write

Because the default encoding of the FTP server is ISO-8859-1, when the client gets the file information

You need to request the server to use UTF-8 encoding (if the server supports it). If the server does not support enabling UTF-8 encoding, then the client needs to specify a string encoding format.

When the client requests the remotePath path and gets the file name, it needs to transcode the path.

String remotePath = "/ upload/qjnn.apk"; / / the file path on the FTP server String charSet = "UTF-8"; if (! FTPReply.isPositiveCompletion (client.sendCommand ("OPTS UTF8", "ON")) {/ / request to the server to use "UTF-8" encoding charSet = "GBK";} FTPFile [] files = client.listFiles (remotePath.getBytes (charSet), "ISO-8859-1")) / / A pair of remotePath transcoding FTPFile file = files [0]; / / file information long size = file.getSize (); String fileaName = new String (fileName.getBytes (), Charset.forName (charSet))

Through the above code, you can get the correct file information.

File download

Configure the download interval for each thread

Long fileLength = mEntity.getFileSize (); Properties pro = CommonUtil.loadConfig (mConfigFile); int blockSize = (int) (fileLength / mThreadNum); int [] recordL = new int [mThreadNum]; for (int I = 0; I

< mThreadNum; i++) { recordL[i] = -1;}int rl = 0;for (int i = 0; i < mThreadNum; i++) { long startL = i * blockSize, endL = (i + 1) * blockSize; Object state = pro.getProperty(mTempFile.getName() + "_state_" + i); if (state != null && Integer.parseInt(state + "") == 1) { //该线程已经完成 if (resumeRecordLocation(i, startL, endL)) return; continue; } //分配下载位置 Object record = pro.getProperty(fileName + "_record_" + i); //如果有记录,则恢复下载 if (record != null && Long.parseLong(record + "") >

= 0) {Long r = Long.parseLong (record + "); mConstance.CURRENT_LOCATION + = r-startL; Log.d (TAG," task ["+ mEntity.getFileName () +"] thread _ _ "+ I +" _ _ resume download "); startL = r; recordL [rl] = I; rl++;} else {recordL [rl] = I; rl++ } / / the end position of the last thread is the total length of the file if (I = = (mThreadNum-1)) endL = fileLength; / / create the segmentation thread AbsThreadTask task = createSingThreadTask (I, startL, endL, fileLength); if (task = = null) return; mTask.put (I, task);} startSingleTask (recordL)

In the above code, there are two main steps:

Before downloading the file, read the download status of each thread currently downloaded from the local file

If the download record exists, start the download from the record location, and if the record does not exist, restart the download

Automatic stop of FTP segmented thread interval

Because there is no interval download in FTP protocol, in order to allow the thread to download only the contents of a specific interval, the client needs to stop the thread when the cumulative data length read by a single thread has exceeded the assigned interval length.

Client.enterLocalPassiveMode (); / / set the passive mode client.setFileType (FTP.BINARY_FILE_TYPE); / / set the file transfer mode client.setRestartOffset (mConfig.START_LOCATION); / / set the location to resume the download client.allocate (mBufSize); is = client.retrieveFileStream (remotePath.getBytes (charSet), SERVER_CHARSET); / / when sending the second instruction, you need to determine reply = client.getReplyCode () again. If (! FTPReply.isPositivePreliminary (reply)) {client.disconnect (); fail (mChildCurrentLocation, "error getting file information, error code:" + reply, null); return;} file = new BufferedRandomAccessFile (mConfig.TEMP_FILE, "rwd", mBufSize); file.seek (mConfig.START_LOCATION); byte [] buffer = new byte [mBufSize]; int len While ((len = is.read (buffer))! =-1) {/ / if the thread reads data length greater than the assigned interval length, it can only read the maximum interval length if (mChildCurrentLocation + len > = mConfig.END_LOCATION) {len = (int) (mConfig.END_LOCATION-mChildCurrentLocation); file.write (buffer, 0, len); progress (len); break } else {file.write (buffer, 0, len); progress (len);}}

Here are a few more holes to deal with:

For FTP clients, it is generally necessary to set the difference between passive mode, passive mode and active mode

After getting the file stream, you need to use FTPReply.isPositivePreliminary (reply) to make a second command judgment.

About FTP file upload

The principle of resuming FTP files at breakpoints is similar to that of downloads:

The stop location is recorded when the download is stopped, and the breakpoint is restored from the specified location through the REST command when the download starts again.

You need to get the file information before the task is executed and compare the files on the server.

What is different from downloading is:

When uploading FTP, you need to specify a working directory and create a folder on a remote server

The server is required to open, delete and read IO to the user, otherwise there will be 550th permission error.

This is the end of the article on "how to use FTP to achieve multithreaded breakpoint download and upload function in Android". Thank you for reading! I believe that everyone has a certain understanding of "how to use FTP to achieve multithreaded breakpoint download and upload function in Android". If you still want to learn more knowledge, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report