java ftp 文件下载 中文乱码
时间: 2023-10-17 13:29:36 浏览: 139
你可以尝试在下载文件之前设置字符编码为UTF-8,这样可以避免中文乱码的问题。在使用FTP进行文件下载时,可以使用`setControlEncoding`方法来设置字符编码。以下是一个示例代码:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FTPDownloadExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String user = "username";
String password = "password";
String remoteFilePath = "/path/to/remote/file.txt";
String localFilePath = "/path/to/local/file.txt";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, password);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("UTF-8");
OutputStream outputStream = new FileOutputStream(localFilePath);
ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.close();
System.out.println("文件下载成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout(); ftpClient.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
请将上述代码中的`server`、`port`、`user`、`password`、`remoteFilePath`和`localFilePath`替换为你实际的FTP服务器信息和文件路径。
阅读全文