java ftp上传大文件 并打印上传进度信息 百分比
时间: 2023-08-07 21:08:29 浏览: 129
以下是Java代码示例,演示如何上传大文件到FTP服务器并打印上传进度信息(百分比):
```java
import java.io.*;
import org.apache.commons.net.ftp.*;
public class FTPUploader {
private FTPClient ftpClient;
public FTPUploader() {
ftpClient = new FTPClient();
}
public void uploadFile(String host, String port, String username, String password, String remotePath, String localPath) throws IOException {
int reply;
ftpClient.connect(host, Integer.parseInt(port));
ftpClient.login(username, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
throw new IOException("Failed to connect to FTP Server");
}
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.changeWorkingDirectory(remotePath);
File localFile = new File(localPath);
long fileSize = localFile.length();
long uploadedSize = 0;
InputStream inputStream = new FileInputStream(localFile);
OutputStream outputStream = ftpClient.storeFileStream(localFile.getName());
byte[] buffer = new byte[1024];
int bytesRead;
long startTime = System.currentTimeMillis();
long currentTime = startTime;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
uploadedSize += bytesRead;
int progress = (int) ((uploadedSize / (float) fileSize) * 100);
long elapsedTime = System.currentTimeMillis() - currentTime;
if (elapsedTime > 1000) { // 每秒钟打印一次上传进度信息
System.out.println("File upload progress: " + progress + "%");
currentTime = System.currentTimeMillis();
}
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
long endTime = System.currentTimeMillis();
System.out.println("File uploaded successfully in " + (endTime - startTime) + " ms");
}
}
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
}
```
要使用此类上传文件,请执行以下步骤:
```java
String host = "ftp.example.com";
String port = "21";
String username = "username";
String password = "password";
String remotePath = "/remote/path";
String localPath = "/local/path/file.txt";
FTPUploader uploader = new FTPUploader();
uploader.uploadFile(host, port, username, password, remotePath, localPath);
uploader.disconnect();
```
请注意,此示例代码仅适用于上传二进制文件。如果您需要上传文本文件,请更改以下行:
```java
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
```
为:
```java
ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
```
阅读全文
相关推荐
















