찾다
Javajava지도 시간JAVA SFTP 파일 업로드, 다운로드 및 일괄 다운로드 예제 코드에 대한 자세한 설명

이 글은 주로 JAVA SFTP 파일 업로드 , 다운로드, 일괄 다운로드 예시를 소개하고 있으니 관심 있는 친구들이 참고해 보세요.

1.jsch 공식 API주소 보기(첨부파일은 필수 jar입니다)

http : //www.jcraft.com/jsch/

2.jsch소개

JSch(Java 보안 채널)는 SSH2 순수 Java 구현. 이를 통해 SSH 서버에 연결하고 포트 전달, X11 전달, 파일 전송 등을 사용할 수 있습니다. 물론 해당 기능을 자신의 애플리케이션에 통합할 수도 있습니다.

SFTP(보안 파일 전송 프로토콜)보안파일 전송 프로토콜입니다. 파일 전송을 위한 안전한 암호화 방법을 제공합니다. SFTP는 SSH의 일부이며 파일을 서버로 안전하게 전송하는 방법이지만 전송 효율성은 일반 FTP보다 낮습니다.

3. 일반적으로 사용되는 API 방법:

  • put(): 파일 업로드

  • get (): 파일 다운로드

  • cd(): 지정된 디렉터리를 입력합니다.

  • ls(): 지정된 디렉터리를 가져옵니다. 디렉토리 파일 목록

  • rename(): 지정된 파일 또는 디렉토리의 이름을 바꿉니다.

  • rm(): 지정된 을 삭제합니다. file

  • mkdir(): 디렉터리 생성

  • rmdir(): 디렉터리 삭제

  • 여러 개의 오버로드된 메서드를 넣고 가져오려면 소스 코드를 직접 살펴보세요.

4. 공통 메서드 사용 및 캡슐화 Into a util class


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
/**
 * sftp工具类
 * 
 * @author xxx
 * @date 2014-6-17
 * @time 下午1:39:44
 * @version 1.0
 */
public class SFTPUtils
{
  private static Logger log = Logger.getLogger(SFTPUtils.class.getName());

  private String host;//服务器连接ip
  private String username;//用户名
  private String password;//密码
  private int port = 22;//端口号
  private ChannelSftp sftp = null;
  private Session sshSession = null;

  public SFTPUtils(){}

  public SFTPUtils(String host, int port, String username, String password)
  {
    this.host = host;
    this.username = username;
    this.password = password;
    this.port = port;
  }

  public SFTPUtils(String host, String username, String password)
  {
    this.host = host;
    this.username = username;
    this.password = password;
  }

  /**
   * 通过SFTP连接服务器
   */
  public void connect()
  {
    try
    {
      JSch jsch = new JSch();
      jsch.getSession(username, host, port);
      sshSession = jsch.getSession(username, host, port);
      if (log.isInfoEnabled())
      {
        log.info("Session created.");
      }
      sshSession.setPassword(password);
      Properties sshConfig = new Properties();
      sshConfig.put("StrictHostKeyChecking", "no");
      sshSession.setConfig(sshConfig);
      sshSession.connect();
      if (log.isInfoEnabled())
      {
        log.info("Session connected.");
      }
      Channel channel = sshSession.openChannel("sftp");
      channel.connect();
      if (log.isInfoEnabled())
      {
        log.info("Opening Channel.");
      }
      sftp = (ChannelSftp) channel;
      if (log.isInfoEnabled())
      {
        log.info("Connected to " + host + ".");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  /**
   * 关闭连接
   */
  public void disconnect()
  {
    if (this.sftp != null)
    {
      if (this.sftp.isConnected())
      {
        this.sftp.disconnect();
        if (log.isInfoEnabled())
        {
          log.info("sftp is closed already");
        }
      }
    }
    if (this.sshSession != null)
    {
      if (this.sshSession.isConnected())
      {
        this.sshSession.disconnect();
        if (log.isInfoEnabled())
        {
          log.info("sshSession is closed already");
        }
      }
    }
  }

  /**
   * 批量下载文件
   * @param remotPath:远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
   * @param localPath:本地保存目录(以路径符号结束,D:\Duansha\sftp\)
   * @param fileFormat:下载文件格式(以特定字符开头,为空不做检验)
   * @param fileEndFormat:下载文件格式(文件格式)
   * @param del:下载后是否删除sftp文件
   * @return
   */
  public List<String> batchDownLoadFile(String remotePath, String localPath,
      String fileFormat, String fileEndFormat, boolean del)
  {
    List<String> filenames = new ArrayList<String>();
    try
    {
      // connect();
      Vector v = listFiles(remotePath);
      // sftp.cd(remotePath);
      if (v.size() > 0)
      {
        System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
        Iterator it = v.iterator();
        while (it.hasNext())
        {
          LsEntry entry = (LsEntry) it.next();
          String filename = entry.getFilename();
          SftpATTRS attrs = entry.getAttrs();
          if (!attrs.isDir())
          {
            boolean flag = false;
            String localFileName = localPath + filename;
            fileFormat = fileFormat == null ? "" : fileFormat
                .trim();
            fileEndFormat = fileEndFormat == null ? ""
                : fileEndFormat.trim();
            // 三种情况
            if (fileFormat.length() > 0 && fileEndFormat.length() > 0)
            {
              if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat))
              {
                flag = downloadFile(remotePath, filename,localPath, filename);
                if (flag)
                {
                  filenames.add(localFileName);
                  if (flag && del)
                  {
                    deleteSFTP(remotePath, filename);
                  }
                }
              }
            }
            else if (fileFormat.length() > 0 && "".equals(fileEndFormat))
            {
              if (filename.startsWith(fileFormat))
              {
                flag = downloadFile(remotePath, filename, localPath, filename);
                if (flag)
                {
                  filenames.add(localFileName);
                  if (flag && del)
                  {
                    deleteSFTP(remotePath, filename);
                  }
                }
              }
            }
            else if (fileEndFormat.length() > 0 && "".equals(fileFormat))
            {
              if (filename.endsWith(fileEndFormat))
              {
                flag = downloadFile(remotePath, filename,localPath, filename);
                if (flag)
                {
                  filenames.add(localFileName);
                  if (flag && del)
                  {
                    deleteSFTP(remotePath, filename);
                  }
                }
              }
            }
            else
            {
              flag = downloadFile(remotePath, filename,localPath, filename);
              if (flag)
              {
                filenames.add(localFileName);
                if (flag && del)
                {
                  deleteSFTP(remotePath, filename);
                }
              }
            }
          }
        }
      }
      if (log.isInfoEnabled())
      {
        log.info("download file is success:remotePath=" + remotePath
            + "and localPath=" + localPath + ",file size is"
            + v.size());
      }
    }
    catch (SftpException e)
    {
      e.printStackTrace();
    }
    finally
    {
      // this.disconnect();
    }
    return filenames;
  }

  /**
   * 下载单个文件
   * @param remotPath:远程下载目录(以路径符号结束)
   * @param remoteFileName:下载文件名
   * @param localPath:本地保存目录(以路径符号结束)
   * @param localFileName:保存文件名
   * @return
   */
  public boolean downloadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
  {
    FileOutputStream fieloutput = null;
    try
    {
      // sftp.cd(remotePath);
      File file = new File(localPath + localFileName);
      // mkdirs(localPath + localFileName);
      fieloutput = new FileOutputStream(file);
      sftp.get(remotePath + remoteFileName, fieloutput);
      if (log.isInfoEnabled())
      {
        log.info("===DownloadFile:" + remoteFileName + " success from sftp.");
      }
      return true;
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (SftpException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (null != fieloutput)
      {
        try
        {
          fieloutput.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
    return false;
  }

  /**
   * 上传单个文件
   * @param remotePath:远程保存目录
   * @param remoteFileName:保存文件名
   * @param localPath:本地上传目录(以路径符号结束)
   * @param localFileName:上传的文件名
   * @return
   */
  public boolean uploadFile(String remotePath, String remoteFileName,String localPath, String localFileName)
  {
    FileInputStream in = null;
    try
    {
      createDir(remotePath);
      File file = new File(localPath + localFileName);
      in = new FileInputStream(file);
      sftp.put(in, remoteFileName);
      return true;
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (SftpException e)
    {
      e.printStackTrace();
    }
    finally
    {
      if (in != null)
      {
        try
        {
          in.close();
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
    return false;
  }

  /**
   * 批量上传文件
   * @param remotePath:远程保存目录
   * @param localPath:本地上传目录(以路径符号结束)
   * @param del:上传后是否删除本地文件
   * @return
   */
  public boolean bacthUploadFile(String remotePath, String localPath,
      boolean del)
  {
    try
    {
      connect();
      File file = new File(localPath);
      File[] files = file.listFiles();
      for (int i = 0; i < files.length; i++)
      {
        if (files[i].isFile()
            && files[i].getName().indexOf("bak") == -1)
        {
          if (this.uploadFile(remotePath, files[i].getName(),
              localPath, files[i].getName())
              && del)
          {
            deleteFile(localPath + files[i].getName());
          }
        }
      }
      if (log.isInfoEnabled())
      {
        log.info("upload file is success:remotePath=" + remotePath
            + "and localPath=" + localPath + ",file size is "
            + files.length);
      }
      return true;
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      this.disconnect();
    }
    return false;

  }

  /**
   * 删除本地文件
   * @param filePath
   * @return
   */
  public boolean deleteFile(String filePath)
  {
    File file = new File(filePath);
    if (!file.exists())
    {
      return false;
    }

    if (!file.isFile())
    {
      return false;
    }
    boolean rs = file.delete();
    if (rs && log.isInfoEnabled())
    {
      log.info("delete file success from local.");
    }
    return rs;
  }

  /**
   * 创建目录
   * @param createpath
   * @return
   */
  public boolean createDir(String createpath)
  {
    try
    {
      if (isDirExist(createpath))
      {
        this.sftp.cd(createpath);
        return true;
      }
      String pathArry[] = createpath.split("/");
      StringBuffer filePath = new StringBuffer("/");
      for (String path : pathArry)
      {
        if (path.equals(""))
        {
          continue;
        }
        filePath.append(path + "/");
        if (isDirExist(filePath.toString()))
        {
          sftp.cd(filePath.toString());
        }
        else
        {
          // 建立目录
          sftp.mkdir(filePath.toString());
          // 进入并设置为当前目录
          sftp.cd(filePath.toString());
        }

      }
      this.sftp.cd(createpath);
      return true;
    }
    catch (SftpException e)
    {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * 判断目录是否存在
   * @param directory
   * @return
   */
  public boolean isDirExist(String directory)
  {
    boolean isDirExistFlag = false;
    try
    {
      SftpATTRS sftpATTRS = sftp.lstat(directory);
      isDirExistFlag = true;
      return sftpATTRS.isDir();
    }
    catch (Exception e)
    {
      if (e.getMessage().toLowerCase().equals("no such file"))
      {
        isDirExistFlag = false;
      }
    }
    return isDirExistFlag;
  }

  /**
   * 删除stfp文件
   * @param directory:要删除文件所在目录
   * @param deleteFile:要删除的文件
   * @param sftp
   */
  public void deleteSFTP(String directory, String deleteFile)
  {
    try
    {
      // sftp.cd(directory);
      sftp.rm(directory + deleteFile);
      if (log.isInfoEnabled())
      {
        log.info("delete file success from sftp.");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }

  /**
   * 如果目录不存在就创建目录
   * @param path
   */
  public void mkdirs(String path)
  {
    File f = new File(path);

    String fs = f.getParent();

    f = new File(fs);

    if (!f.exists())
    {
      f.mkdirs();
    }
  }

  /**
   * 列出目录下的文件
   * 
   * @param directory:要列出的目录
   * @param sftp
   * @return
   * @throws SftpException
   */
  public Vector listFiles(String directory) throws SftpException
  {
    return sftp.ls(directory);
  }

  public String getHost()
  {
    return host;
  }

  public void setHost(String host)
  {
    this.host = host;
  }

  public String getUsername()
  {
    return username;
  }

  public void setUsername(String username)
  {
    this.username = username;
  }

  public String getPassword()
  {
    return password;
  }

  public void setPassword(String password)
  {
    this.password = password;
  }

  public int getPort()
  {
    return port;
  }

  public void setPort(int port)
  {
    this.port = port;
  }

  public ChannelSftp getSftp()
  {
    return sftp;
  }

  public void setSftp(ChannelSftp sftp)
  {
    this.sftp = sftp;
  }
  
  /**测试*/
  public static void main(String[] args)
  {
    SFTPUtils sftp = null;
    // 本地存放地址
    String localPath = "D:/tomcat5/webapps/ASSESS/DocumentsDir/DocumentTempDir/txtData/";
    // Sftp下载路径
    String sftpPath = "/home/assess/sftp/jiesuan_2/2014/";
    List<String> filePathList = new ArrayList<String>();
    try
    {
      sftp = new SFTPUtils("10.163.201.115", "tdcp", "tdcp");
      sftp.connect();
      // 下载
      sftp.batchDownLoadFile(sftpPath, localPath, "ASSESS", ".txt", true);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    finally
    {
      sftp.disconnect();
    }
  }
}

5. 필요할 때 보조클래스, 그런데 적어두시면 다음에 바로 사용하실 수 있어요


아아아아

위 내용은 JAVA SFTP 파일 업로드, 다운로드 및 일괄 다운로드 예제 코드에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
플랫폼 독립성은 기업 수준의 Java 응용 프로그램에 어떻게 도움이됩니까?플랫폼 독립성은 기업 수준의 Java 응용 프로그램에 어떻게 도움이됩니까?May 03, 2025 am 12:23 AM

Java는 플랫폼 독립성으로 인해 엔터프라이즈 수준의 응용 프로그램에서 널리 사용됩니다. 1) 플랫폼 독립성은 JVM (Java Virtual Machine)을 통해 구현되므로 JAVA를 지원하는 모든 플랫폼에서 코드가 실행될 수 있습니다. 2) 크로스 플랫폼 배포 및 개발 프로세스를 단순화하여 유연성과 확장 성을 더 많이 제공합니다. 3) 그러나 성능 차이 및 타사 라이브러리 호환성에주의를 기울이고 순수한 Java 코드 사용 및 크로스 플랫폼 테스트와 같은 모범 사례를 채택해야합니다.

Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?Java는 플랫폼 독립성을 고려하여 IoT (Internet of Things) 장치의 개발에서 어떤 역할을합니까?May 03, 2025 am 12:22 AM

javaplaysaSignificantroleiniotduetoitsplatformincentence.1) itallowscodetobewrittenonceandevices.2) java'secosystemprovidesusefullibrariesforiot.3) itssecurityfeaturesenhanceiotiotsystemsafety.hormormory.hormory.hustupletety.houghmormory

Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.Java에서 플랫폼 별 문제를 발견 한 시나리오와 해결 방법을 설명하십시오.May 03, 2025 am 12:21 AM

thejava.nio.filepackage.1) withsystem.getProperty ( "user.dir") andtherelativeatthereplattHefilePsiple.2) thepathtopilebtoafne 컨버터링 주제

개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?개발자를위한 Java의 플랫폼 독립성의 이점은 무엇입니까?May 03, 2025 am 12:15 AM

Java'SplatformIndenceSnictIficantIficantBecauseItAllowsDeveloperstowRiteCodeOnceAntOnitonAnyplatformwithajvm.이 "WriteOnce, Runanywhere"(WORA) 접근자 : 1) 교차 플랫폼 컴퓨팅 성, DeploymentAcrossDifferentoSwithoutissswithoutissuesswithoutissuesswithoutswithoutisssues를 활성화합니다

다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?다른 서버에서 실행 해야하는 웹 애플리케이션에 Java를 사용하는 장점은 무엇입니까?May 03, 2025 am 12:13 AM

Java는 크로스 서버 웹 응용 프로그램을 개발하는 데 적합합니다. 1) Java의 "Write Once, Run Everywhere"철학은 JVM을 지원하는 모든 플랫폼에서 코드를 실행합니다. 2) Java는 Spring 및 Hibernate와 같은 도구를 포함하여 개발 프로세스를 단순화하는 풍부한 생태계를 가지고 있습니다. 3) Java는 성능 및 보안에서 훌륭하게 성능을 발휘하여 효율적인 메모리 관리 및 강력한 보안 보증을 제공합니다.

JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?JVM은 Java의 'Write Once, Run Aloneeringly'(Wora) 기능에 어떻게 기여합니까?May 02, 2025 am 12:25 AM

JVM은 바이트 코드 해석, 플랫폼 독립 API 및 동적 클래스 로딩을 통해 Java의 Wora 기능을 구현합니다. 1. 바이트 코드는 크로스 플랫폼 작동을 보장하기 위해 기계 코드로 해석됩니다. 2. 표준 API 추상 운영 체제 차이; 3. 클래스는 런타임에 동적으로로드되어 일관성을 보장합니다.

최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?최신 버전의 Java는 플랫폼 별 문제를 어떻게 해결합니까?May 02, 2025 am 12:18 AM

JAVA의 최신 버전은 JVM 최적화, 표준 라이브러리 개선 및 타사 라이브러리 지원을 통해 플랫폼 별 문제를 효과적으로 해결합니다. 1) Java11의 ZGC와 같은 JVM 최적화는 가비지 수집 성능을 향상시킵니다. 2) Java9의 모듈 시스템과 같은 표준 라이브러리 개선은 플랫폼 관련 문제를 줄입니다. 3) 타사 라이브러리는 OpenCV와 같은 플랫폼 최적화 버전을 제공합니다.

JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.JVM이 수행 한 바이트 코드 검증 프로세스를 설명하십시오.May 02, 2025 am 12:18 AM

JVM의 바이트 코드 검증 프로세스에는 네 가지 주요 단계가 포함됩니다. 1) 클래스 파일 형식이 사양을 준수하는지 확인, 2) 바이트 코드 지침의 유효성과 정확성을 확인하고 3) 유형 안전을 보장하기 위해 데이터 흐름 분석을 수행하고 4) 검증의 철저한 성능 균형을 유지합니다. 이러한 단계를 통해 JVM은 안전하고 올바른 바이트 코드 만 실행되도록하여 프로그램의 무결성과 보안을 보호합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기