Java 编写 FTP下载文件的代码,中文内容不能乱码
时间: 2024-02-19 19:57:13 浏览: 68
以下是Java编写FTP下载文件的代码,其中包括了中文内容不乱码的处理:
```java
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.*;
public class FtpDownloadExample {
public static void main(String[] args) {
String server = "ftp.example.com";
int port = 21;
String username = "ftpuser";
String password = "password";
String remoteFilePath = "/remote/file/path.txt";
String localFilePath = "local/file/path.txt";
String encoding = "UTF-8";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(username, password);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, encoding);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
ftpClient.completePendingCommand();
File localFile = new File(localFilePath);
OutputStream outputStream = new FileOutputStream(localFile);
outputStream.write(stringBuilder.toString().getBytes(encoding));
outputStream.close();
ftpClient.logout();
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用了Apache Commons Net库提供的FTPClient类来连接FTP服务器并下载文件。我们将文件类型设置为BINARY_FILE_TYPE,以确保不会发生文件内容的转换。我们使用了InputStreamReader和BufferedReader来读取文件内容,并将编码设置为UTF-8。在将文件内容写入本地文件时,我们使用了OutputStream和FileOutputStream,也将编码设置为UTF-8。这样就能保证在下载中文文件时,不会出现乱码问题。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)