java ftp 复制文件
时间: 2023-08-31 07:08:10 浏览: 190
以下是使用Java实现FTP文件复制的示例代码:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FTPUtil {
private FTPClient ftpClient;
/**
* 连接FTP服务器
*
* @param host FTP服务器地址
* @param port FTP服务器端口号
* @param username FTP登录账号
* @param password FTP登录密码
* @throws IOException
*/
public void connect(String host, int port, String username, String password) throws IOException {
ftpClient = new FTPClient();
ftpClient.connect(host, port);
ftpClient.login(username, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
}
/**
* 复制文件
*
* @param srcFilePath 源文件路径
* @param destFilePath 目标文件路径
* @throws IOException
*/
public void copyFile(String srcFilePath, String destFilePath) throws IOException {
InputStream input = ftpClient.retrieveFileStream(srcFilePath);
OutputStream output = ftpClient.storeFileStream(destFilePath);
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
input.close();
output.close();
boolean success = ftpClient.completePendingCommand();
if (!success) {
throw new IOException("Failed to copy file: " + srcFilePath);
}
}
/**
* 关闭FTP连接
*
* @throws IOException
*/
public void disconnect() throws IOException {
ftpClient.logout();
ftpClient.disconnect();
}
}
```
使用示例:
```java
public class Main {
public static void main(String[] args) {
FTPUtil ftpUtil = new FTPUtil();
try {
ftpUtil.connect("ftp.example.com", 21, "username", "password");
ftpUtil.copyFile("/remote/path/file.txt", "/remote/path/copy_of_file.txt");
ftpUtil.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
请将 "ftp.example.com", "username", "password", "/remote/path/file.txt", "/remote/path/copy_of_file.txt" 替换为您自己的FTP服务器信息和文件路径。
阅读全文