需求说明:将指定文件上传到FTP,上传成功后修改文件名。
获取文件名及路径(这里是从数据库获取,所以前面的代码就不CV了)
/** * 测试上传 * @param map 从数据库获取到的文件信息 (包含文件路径FILE_PATH 文件类型FILE_TYPE等信息) */ public void testUpdFtpFile(Map<String,Object> map){ /*上传附件到FTP*/ FileInputStream inputStream = null; try { //找到要上传的文件 String originfilename = "E:\\work\\files\\"+map.get("FILE_PATH").toString(); //转成流 inputStream = new FileInputStream(originfilename); //上传后的文件名+文件类型 String ftpName = "上传到FTP后的文件名."+map.get("FILE_TYPE"); boolean updFtpFile = FtpClientFile.uploadFile(ftpName,inputStream); if(updFtpFile){ //打印下日志 System.out.println(("=======文件已上传到FTP========")); } } catch (Exception e) { throw new BusinessException("附件上传失败!"); } }
FtpClientFile工具类方法
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; import com.google.gson.JsonArray; /** * ftp 上传文件 * FTPClient commons.net 3.0.1版本 * @author Lenovo * */ public class FtpClientFile { private static final String hostname = "10.xx.xx.xx" ;//FTP IP private static final int port = 21;//FTP 端口号 private static final String username = "ftpName";//FTP 登录账号 private static final String password = "ftpPsd"; //FTP 登录密码 private static final String pathname = "/";//FTP 工作路径 /** * 上传文件(可供Action/Controller层使用) * @param fileName 上传到FTP服务器后的文件名称 * @param inputStream 输入文件流 * @return */ public static boolean uploadFile(String fileName,FileInputStream inputStream){ boolean flag = false; FTPClient ftpClient = new FTPClient(); //设置超时 ftpClient.setConnectTimeout(60*60*1000); //设置编码 ftpClient.setControlEncoding("UTF-8"); try { //连接FTP服务器 ftpClient.connect(hostname, port); //登录FTP服务器 ftpClient.login(username, password); //是否成功登录FTP服务器 int replyCode = ftpClient.getReplyCode(); if(!FTPReply.isPositiveCompletion(replyCode)){ return flag; } System.out.println("===========登录FTP成功了=========="); ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); //切换路径 创建路径 ftpClient.makeDirectory(pathname); ftpClient.changeWorkingDirectory(pathname); ftpClient.enterLocalPassiveMode(); //设置缓冲 ftpClient.setBufferSize(1024 * 1024 * 20); //保持连接 ftpClient.setKeepAlive(true); boolean a = ftpClient.storeFile(new String(fileName.getBytes("utf-8"),"iso-8859-1"), inputStream); if(a){ System.out.println("===========创建文件成功=============="+a); String fileName2 = fileName+"AAA"; boolean status = ftpClient.rename(fileName, fileName2); if(status) System.out.println("===========修改文件名称成功=============="+status); } inputStream.close(); ftpClient.logout(); flag = true; } catch (Exception e) { e.printStackTrace(); } finally{ if(ftpClient.isConnected()){ try { ftpClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } return flag; } /* public static void main(String[] args) { String originfilename = "C:\\Users\\Lenovo\\Desktop\\xx.txt"; FileInputStream inputStream; try { inputStream = new FileInputStream(new File(originfilename)); boolean a = uploadFile("xx.txt","/104/",inputStream); System.out.println("上传文件成功============"+a); } catch (FileNotFoundException e) { e.printStackTrace(); } }*/ }
上传文件到FTP时 注意:是否有权限登录服务器/上传文件等操作。
默认在浏览器输入自己的ftp地址访问下看看 ftp://10.xx.xx.xx:端口号 登录看看
The above is the detailed content of How to upload files to FTP in java. For more information, please follow other related articles on the PHP Chinese website!

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

JRE is the environment in which Java applications run, and its function is to enable Java programs to run on different operating systems without recompiling. The working principle of JRE includes JVM executing bytecode, class library provides predefined classes and methods, configuration files and resource files to set up the running environment.

JVM ensures efficient Java programs run through automatic memory management and garbage collection. 1) Memory allocation: Allocate memory in the heap for new objects. 2) Reference count: Track object references and detect garbage. 3) Garbage recycling: Use the tag-clear, tag-tidy or copy algorithm to recycle objects that are no longer referenced.

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1
Easy-to-use and free code editor