赞
踩
1.ftp上传文件
1.1相关依赖
-
- <dependency>
- <groupId>commons-net</groupId>
- <artifactId>commons-net</artifactId>
- <version>3.6</version>
- </dependency>
1.2工具类
- package com.hungraim.ltc.utils;
- import com.jcraft.jsch.Channel;
- import com.jcraft.jsch.ChannelSftp;
- import com.jcraft.jsch.JSch;
- import com.jcraft.jsch.Session;
- import org.apache.commons.net.ftp.FTP;
- import org.apache.commons.net.ftp.FTPClient;
- import org.apache.commons.net.ftp.FTPConnectionClosedException;
- import org.apache.commons.net.ftp.FTPReply;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Properties;
-
- public class FtpUpload {
- public static void main(String[] args) throws Exception {
- String host = "121.5.28.29";
- Integer port = 22;
- String userName = "user";
- String password = "123456";
- File file = new File("E:\\DevTool\\image\\a.jpg");
- // ftp
- FTPClient ftpClient = new FTPClient();
- // 设置连接使用的字符编码。必须在建立连接之前设置。
- ftpClient.setControlEncoding("UTF-8");
- try {
- // 连接服务端
- ftpClient.connect(host, port);
- System.out.println("连接服务器" + host + ":" + port);
-
- // ftp操作可能会返回一些响应信息,可以打印出来看看
- // showServerReply(ftpClient);
- // 尝试连接后,检查响应码以确认成功
- int replyCode = ftpClient.getReplyCode();
- if (!FTPReply.isPositiveCompletion(replyCode)) {
- disconnectQuietly(ftpClient);
- System.out.println("服务器拒绝连接");
- return;
- }
- } catch (IOException e) {
- disconnectQuietly(ftpClient);
- System.out.println("连接ftp失败");
- e.printStackTrace();
- return;
- }
-
- try {
- // 登录ftp
- boolean success = ftpClient.login(userName, password);
- if (!success) {
- ftpClient.logout();
- System.out.println("客户端登录失败");
- return;
- }
- System.out.println("客户端登录成功");
- // 大部分情况,上传文件时,需要设置这两项
- // 设置文件传输类型为二进制文件类型
- ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
- // 设置被动模式
- ftpClient.enterLocalPassiveMode();
-
-
- boolean done = false;
- try (final InputStream input = new FileInputStream(file)) {
- // 设置上传到ftp上使用的文件名和路径
- String remote = "testUpload/" + file.getName();
- // 上传文件
- done = ftpClient.storeFile(remote, input);
- }
- if (done) {
- System.out.println("上传文件" + file.getName() + "成功");
- // ftpClient.completePendingCommand();
- } else {
- System.out.println("上传文件" + file.getName() + "失败");
- showServerReply(ftpClient);
- }
-
- ftpClient.noop(); // check that control connection is working OK
- ftpClient.logout();
- } catch(FTPConnectionClosedException e) {
- System.out.println("服务端关闭连接");
- e.printStackTrace();
- } catch (IOException e) {
- System.out.println("客户端登录或操作失败");
- e.printStackTrace();
- } finally {
-
- disconnectQuietly(ftpClient);
- }
- }
-
- /**
- * 断开ftp连接
- */
- public static void disconnectQuietly(FTPClient ftpClient) {
- if (ftpClient.isConnected()) {
- try {
- ftpClient.disconnect();
- } catch (IOException ex) {
- // do nothing
- }
- }
- }
-
- /**
- * 打印服务器返回信息
- */
- public static void showServerReply(FTPClient ftpClient) {
- String[] replies = ftpClient.getReplyStrings();
- if (replies != null && replies.length > 0) {
- for (String aReply : replies) {
- System.out.println("服务端响应信息: " + aReply);
- }
- }
- }
- }

ps:如若出现报错,连接ftp失败,在Telnet以及确认无防火墙拦截的情况下,说明服务器不支持ftpClient连接方式。
- org.apache.commons.net.MalformedServerReplyException: Could not parse response code.
- Server Reply: SSH-2.0-OpenSSH_8.0
- at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:344)
- at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:300)
- at org.apache.commons.net.ftp.FTP._connectAction_(FTP.java:438)
- at org.apache.commons.net.ftp.FTPClient._connectAction_(FTPClient.java:962)
- at org.apache.commons.net.ftp.FTPClient._connectAction_(FTPClient.java:950)
- at org.apache.commons.net.SocketClient._connect(SocketClient.java:244)
- at org.apache.commons.net.SocketClient.connect(SocketClient.java:202)
- at com.hungraim.ltc.utils.FtpUpload.main(FtpUpload.java:32)
可以尝试以下方式。
2.sftp上传文件
2.1相关依赖
- <dependency>
- <groupId>com.jcraft</groupId>
- <artifactId>jsch</artifactId>
- <version>0.1.49</version>
- </dependency>
2.2工具类
- package com.hungraim.ltc.utils;
-
- import com.jcraft.jsch.*;
-
- import java.io.*;
- import java.util.Properties;
-
- public class SFTPUtil {
- //用户名
- private String username;
- //密码
- private String password;
- //ip
- private String host;
- //端口一般为22
- private int port;
- //私钥
- private String privateKey;
-
- ChannelSftp sftp = null;
- //通过构造方法传参
- public FileUtil(String username, String password, String host, int port){
- this.username = username;
- this.password = password;
- this.host = host;
- this.port = port;
- }
- public FileUtil(String username, String host, int port, String privateKey){
- this.username = username;
- this.host = host;
- this.port = port;
- this.privateKey = privateKey;
- }
- //登录,检查链接情况
- public void login(){
- try {
- JSch jSch = new JSch();
- if(privateKey != null){
- jSch.addIdentity(privateKey);
- }
- Session session = jSch.getSession(username,host,port);
- if(password != null){
- session.setPassword(password);
- }
- session.setTimeout(100000);
-
- Properties config = new Properties();
- config.put("StrictHostKeyChecking", "no");
- session.setConfig(config);
- session.connect();
-
- Channel channel = session.openChannel("sftp");
- channel.connect();
- sftp = (ChannelSftp) channel;
- System.out.println("登录成功");
- } catch (JSchException e) {
- e.printStackTrace();
- }
-
- }
- //上传文件
- /**
- * @param basePath 目标路径
- * @param direcotry 目标子路径
- * @param sftpFileName 文件名称
- */
- public void upload(String basePath, String direcotry, String sftpFileName, InputStream inputStream) throws SftpException{
- try {
- //进入到目标目录
- sftp.cd(basePath);
- sftp.cd(direcotry);
- } catch (SftpException e) {
- String[] dirs = direcotry.split("/");
- String temPath = basePath;
- for (String dir: dirs) {
- if( null == dir || "".equals(dir)) continue;
- temPath +="/" + dir;
- try {
- sftp.cd(temPath);
- } catch (SftpException ex) {
- sftp.mkdir(temPath);
- sftp.cd(temPath);
- }
- }
- }
- sftp.put(inputStream,sftpFileName);
- System.out.println("上传成功");
- }
- //下载文件
- /**
- * @param directory 下载的文件路径
- * @param downloadFile 下载的文件名
- * @param saveFileDirectory 保存的文件路径
- */
- public void download(String directory, String downloadFile, String saveFileDirectory) throws SftpException, FileNotFoundException{
- if(directory != null && !"".equals(directory)){
- sftp.cd(directory);
- }
- String saveFile = saveFileDirectory + "//" + downloadFile;
- File file = new File(saveFile);
- sftp.get(downloadFile, new FileOutputStream(file));
- System.out.println("下载成功");
- }
- //登出
-
-
-
-
- public static void main(String[] args) throws FileNotFoundException,SftpException {
- FileUtil fiel = new FileUtil("username","pwd","ip",port);
- fiel.login();
- //测试上传功能
- File file = new File("E:\\DevTool\\image\\a.jpg");
- InputStream is = new FileInputStream(file);
- fiel.upload("/projects/gxyx/file","/startSrv","a.jpg",is);
- }
- }

亲测可行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。