Linux安装ftp、Java的FTP上传下载文件工具类

package com.boot.util; import org.apache.commons.net.ftp.FTPClient; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class FtpUtil { private final String host; private final Integer port; private final String username; private final String password; private final String path; public FtpUtil(String host, Integer port, String username, String password, String path) { this.host = host; this.port = port; this.username = username; this.password = password; this.path = path; } private FTPClient getFtpClient() throws IOException { FTPClient ftpClient = new FTPClient(); ftpClient.connect(host, port); ftpClient.login(username, password); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); ftpClient.changeWorkingDirectory(path); return ftpClient; } public void uploadFile(String fileName, InputStream inputStream) throws Exception { FTPClient ftpClient = getFtpClient(); ftpClient.storeFile(new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), inputStream); ftpClient.disconnect(); } public void downloadFile(String fileName, OutputStream outputStream) throws Exception { FTPClient ftpClient = getFtpClient(); try (InputStream inputStream = ftpClient.retrieveFileStream(new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1))) { byte[] buf = new byte[1024]; int read; while ((read = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, read); } ftpClient.disconnect(); } } public static void main(String[] args) throws Exception { FtpUtil ftpUtil = new FtpUtil("****", 21, "****", "****", "****"); ftpUtil.uploadFile("测试文件.txt", Files.newInputStream(Paths.get("C:/file/测试文件.txt"))); try (FileOutputStream outputStream = new FileOutputStream("C:/file/测试文件2.txt")) { ftpUtil.downloadFile("测试文件.txt", outputStream); } } }
上一篇:【高级篇】第7章 Elasticsearch 索引生命周期管理(ILM)


下一篇:Spring Cloud Sentinel