广告
返回顶部
首页 > 资讯 > 后端开发 > Python >java搭建ftp/sftp进行数据传递的全过程
  • 528
分享到

java搭建ftp/sftp进行数据传递的全过程

2024-04-02 19:04:59 528人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

ftp/sftp概念及搭建 ftp是一种文件传输协议,让客户端和服务端能够互相传递文件,图片等数据;方便快捷; sftp是ssh file transfer protocol缩写,

ftp/sftp概念及搭建

ftp是一种文件传输协议,让客户端和服务端能够互相传递文件,图片等数据;方便快捷;
sftp是ssh file transfer protocol缩写,也是一种文件传输协议.sftp比ftp安全的多,但传输效率要低的多

搭建:
ftp可以搜索网上教程,很多,在此不过多赘述

在这里插入图片描述

创建完成后,通过浏览器就可以访问到内容了;

sftp用freesshd搭建(记得freesshd的安装路径不要有中文,否则各种报错);这个也可以自行百度,解决方法很多;

Java代码


代码如下:
import java.io.*;
import java.net.SocketException; 
import java.util.ArrayList;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

public class FTPClientTest
{

    private  static String userName; // FTP 登录用户名
    private static String passWord; // FTP 登录密码
    private static String ip;// FTP 服务器地址IP地址
    private  static int port; // FTP 端口

    //构造函数初始化
    public FTPClientTest(String userName,String password,String ip,int port){
    	this.userName=userName;
    	this.password=password;
    	this.ip=ip;
    	this.port=port;
    }
    public static String getUserName(){ return userName;}
    public static void setUserName(String userName) {FTPClientTest.userName = userName; } 
    public static String getPassword() {return password;}
    public static void setPassword(String password){FTPClientTest.password = password;}
    public static String getIp() { return ip; }
    public static void setIp(String ip){FTPClientTest.ip = ip;}
    public static int getPort() {return port; }
    public static void setPort(int port) {FTPClientTest.port = port;}
    private static FTPClient ftpClient = null; // FTP 客户端代理
    
    
    public boolean connectServer()
    {
    	 System.out.println("进行连接");
         boolean flag = true;
         if (ftpClient == null)
         {
             int reply;
             try
             {
                 System.out.println("初始化连接");
                 ftpClient = new FTPClient();
                 String LOCAL_CHARSET = "GBK";
                 System.out.println("设置IP和端口");
                 ftpClient.connect(ip, port);
                 System.out.println("设置密码");
                 ftpClient.login(userName, password);
                 System.out.println("进行连接");
                 reply = ftpClient.getReplyCode();
                 ftpClient.setDataTimeout(120000);
                 System.out.println("设置编码操作方式");
                 if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
                 {
                     LOCAL_CHARSET = "UTF-8";
                 }
                 System.out.println("设置编码操作方式1");
                 ftpClient.setControlEncoding(LOCAL_CHARSET);
                 System.out.println("是否连接成功");
                 if (!FTPReply.isPositiveCompletion(reply))
                 {
                     ftpClient.disconnect();
                     System.out.println("FTP 服务拒绝连接!");
                     flag = false;
                 }
             }
             catch (SocketException e)
             {
                 flag = false;
                 e.printStackTrace();
                 System.out.println("登录ftp服务器 " + ip + " 失败,连接超时!");
             }
             catch (IOException e)
             {
                 flag = false;
                 e.printStackTrace();
                 System.out.println("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");
             }
             catch (Exception e)
             {
                 flag = false;
                 e.printStackTrace();
                 // System.out.println("登录ftp服务器 " + ip + " 失败,FTP服务器无法打开!");
             }
         }
         return flag;
    }
    
    
   
    public boolean uploadFile(String remoteFile1, File localFile)
    {
    	boolean flag = false;
        
        try
        {
            InputStream in = new FileInputStream(localFile);
            String remote = new String(remoteFile1.getBytes("UTF-8"), "iso-8859-1");
            if (ftpClient.storeFile(remote, in))
            {
                flag = true;
                System.out.println(localFile.getAbsolutePath() + "上传文件成功!");
            }
            else
            {
                System.out.println(localFile.getAbsolutePath() + "上传文件失败!");
            }
            in.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return flag;
    }
    
    
    public boolean uploadFile(String local, String remote)
    {
        
        boolean flag = true;
        String remoteFileName = remote;
        if (remote.contains("/"))
        {
            remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
            // 创建服务器远程目录结构,创建失败直接返回
            if (!CreateDirecroty(remote))
            {
                return false;
            }
        }
        File f = new File(local);
        if (!uploadFile(remoteFileName, f))
        {
            flag = false;
        }
        
        return flag;
    }
    
    
    public ArrayList<String> uploadManyFile(String filename, String uploadpath)
    {
        boolean flag = true;
        ArrayList<String> l = new ArrayList<String>();
        StringBuffer strBuf = new StringBuffer();
        int n = 0; // 上传失败的文件个数
        int m = 0; // 上传成功的文件个数
        try
        {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.changeWorkingDirectory("/");
            File file = new File(filename);
            File fileList[] = file.listFiles();
            
            for (File upfile : fileList)
            {
                if (!upfile.isDirectory())
                {
                    String local = upfile.getCanonicalPath().replaceAll("\\\\", "/");
                    String temp = upfile.getCanonicalPath();
                    String a = temp.replace(filename + "\\", "");
                    String remote = uploadpath.replaceAll("\\\\", "/") + a;
                    flag = uploadFile(local, remote);
                    ftpClient.changeWorkingDirectory("/");
                }
                if (!flag)
                {
                    n++;
                    strBuf.append(upfile.getName() + ",");
                    System.out.println("文件[" + upfile.getName() + "]上传失败");
                }
                else
                {
                    m++;
                }
            }
            l.add("失败个数" + n);
            l.add("成功个数" + m);
            l.add(strBuf.toString());
        }
        catch (NullPointerException e)
        {
            e.printStackTrace();
            System.out.println("本地文件上传失败!找不到上传文件!" + e);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("本地文件上传失败!" + e);
        }
        return l;
    }
 
    
    public   boolean  loadFile(String remoteFileName, String localFileName)
    {
        
        boolean flag = true;
        // 下载文件
        BufferedOutputStream buffOut = null;
        try
        {
            buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
            flag = ftpClient.retrieveFile(new String(remoteFileName.getBytes("UTF-8"), "iso-8859-1"), buffOut);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("本地文件下载失败!" + e);
        }
        finally
        {
            try
            {
                if (buffOut != null)
                    buffOut.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return flag;
        
    }
    
    
    public boolean deleteFile(String filename)
    {
        boolean flag = true;
        try
        {
            flag = ftpClient.deleteFile(new String(filename.getBytes("UTF-8"), "iso-8859-1"));
            if (flag)
            {
                System.out.println("删除文件" + filename + "成功!");
            }
            else
            {
                System.out.println("删除文件" + filename + "成功!");
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        return flag;
    }
    
    
    public void deleteEmptyDirectory(String pathname)
    {
        
        try
        {
            ftpClient.removeDirectory(new String(pathname.getBytes("UTF-8"), "iso-8859-1"));
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        } 
        
    }
    
    
    public String[] listRemoteAllFiles()
    {
    	try
        {
            String[] names = ftpClient.listNames();
            
            for (int i = 0; i < names.length; i++)
            {
                System.out.println(names[i]);
            }
            return names;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    
    
    public void closeConnect()
    {
    	try
        {
            if (ftpClient != null)
            {
                ftpClient.loGout();
                ftpClient.disconnect();
                ftpClient=null;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }        
    }
    
    
    public void setFileType(int fileType1)
    {
    	try
        {
            int a = FTP.BINARY_FILE_TYPE;
            if (fileType1 == 1)
            {
                a = FTP.ASCII_FILE_TYPE;
            }
            ftpClient.setFileType(a);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
      
    }
    
    
    public boolean changeWorkingDirectory(String directory)
    {
        boolean flag = true;
        try
        {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag)
            {
                System.out.println("进入文件夹" + directory + " 成功!");
            }
            else
            {
                System.out.println("进入文件夹" + directory + " 失败!");
            }
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        return flag;
    }
    
    
    public void changeToParentDirectory()
    {
    	 try
         {
             ftpClient.changeToParentDirectory();
         }
         catch (IOException ioe)
         {
             ioe.printStackTrace();
         }
        
    }
    
    
    public void renameFile(String oldFileName, String newFileName)
    {
        try
        {
            System.out.println(oldFileName);
            System.out.println(newFileName);
            ftpClient.rename(new String(oldFileName.getBytes("UTF-8"), "iso-8859-1"), new String(newFileName.getBytes("UTF-8"), "iso-8859-1"));
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }
    
    
    @SuppressWarnings("unused")
	private FTPClientConfig getFtpConfig()
    {
    	 FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
         ftpConfig.setServerLanguageCode(FTP.DEFAULT_CONTROL_ENCODING);
         return ftpConfig;
    }
    
    
    @SuppressWarnings("unused")
	private String iso8859togbk(Object obj)
    {
        try
        {
            if (obj == null)
                return "";
            else
                return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
        }
        catch (Exception e)
        {
            return "";
        }
        
    }
    
    
    public boolean makeDirectory(String dir)
    {
        boolean flag = true;
        try
        {
            flag = ftpClient.makeDirectory(dir);
            if (flag)
            {
                System.out.println("创建文件夹" + dir + " 成功!");
                
            }
            else
            {
                System.out.println("创建文件夹" + dir + " 失败!");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return flag;
    }
    
    
    public boolean CreateDirecroty(String remote)
    {
        boolean success = true;
        try
        {
            String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
            // 如果远程目录不存在,则递归创建远程服务器目录
            if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory)))
            {
                int start = 0;
                int end = 0;
                if (directory.startsWith("/"))
                {
                    start = 1;
                }
                else
                {
                    start = 0;
                }
                end = directory.indexOf("/", start);
                
                while (true)
                {
                    String subDirectory;
                    subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                    
                    if (!changeWorkingDirectory(subDirectory))
                    {
                        if (makeDirectory(subDirectory))
                        {
                            changeWorkingDirectory(subDirectory);
                        }
                        else
                        {
                            System.out.println("创建目录[" + subDirectory + "]失败");
                            System.out.println("创建目录[" + subDirectory + "]失败");
                            success = false;
                            return success;
                        }
                    }
                    start = end + 1;
                    end = directory.indexOf("/", start);
                    // 检查所有目录是否创建完毕
                    if (end <= start)
                    {
                        break;
                    }
                }
            }
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return success;
    }
}

ftp测试代码如下:


public class test {
	public static void main(String[] args) {
		FTPClientTest ftp=new FTPClientTest("user", "548", "168.125.256.22", 21);
		boolean b=ftp.connectServer();
		System.out.println(b);
		
		System.out.println(ftp.listRemoteAllFiles());
		
		System.out.println(ftp.uploadFile("F:/home/b.txt", "/c.txt"));
		System.out.println(ftp.loadFile("/a.txt", "F:/home/b.txt"));
		ftp.closeConnect();
	}
}

输出结果如下:

在这里插入图片描述

成功了;

sftp搭建完成后,也测试下,至于搭建过程,自行百度好啦

在这里插入图片描述

看到没,连接成功了;我用我的电脑模拟的;

--结束END--

本文标题: java搭建ftp/sftp进行数据传递的全过程

本文链接: https://www.lsjlt.com/news/129639.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • java搭建ftp/sftp进行数据传递的全过程
    ftp/sftp概念及搭建 ftp是一种文件传输协议,让客户端和服务端能够互相传递文件,图片等数据;方便快捷; sftp是ssh file transfer protocol缩写,...
    99+
    2022-11-12
  • 如何使用java搭建ftp/sftp进行数据传递
    这篇文章将为大家详细讲解有关如何使用java搭建ftp/sftp进行数据传递,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。ftp/sftp概念及搭建ftp是一种文件传输协议,让客户端和服务端能够互相传递文...
    99+
    2023-06-20
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作