Android ftp 断点续传java代码示例
时间: 2023-10-13 22:28:10 浏览: 147
好的,以下是一个简单的 Android ftp 断点续传的 Java 代码示例:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FtpUtil {
private static final int BUFFER_SIZE = 1024 * 1024;
public static boolean uploadFile(String host, int port, String username, String password,
String remoteDir, String remoteFileName, String localFilePath) {
FTPClient ftpClient = new FTPClient();
boolean success = false;
try {
ftpClient.connect(host, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
ftpClient.changeWorkingDirectory(remoteDir);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setBufferSize(BUFFER_SIZE);
long remoteSize = 0;
FTPFile[] files = ftpClient.listFiles(remoteFileName);
if (files.length == 1) {
remoteSize = files[0].getSize();
}
OutputStream outputStream = ftpClient.appendFileStream(remoteFileName);
if (outputStream == null) {
outputStream = ftpClient.storeFileStream(remoteFileName);
}
byte[] bytes = new byte[BUFFER_SIZE];
int length;
long step = localFile.length() / 100;
long process = remoteSize / step;
while ((length = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, length);
remoteSize += length;
long currentProcess = remoteSize / step;
if (currentProcess > process) {
process = currentProcess;
if (process % 10 == 0) {
System.out.println("上传进度:" + process);
}
}
}
outputStream.flush();
inputStream.close();
outputStream.close();
success = ftpClient.completePendingCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
}
```
希望能够帮到你!
阅读全文