java、sftp文件服务器的操作(获取链接。上传、下载,删除,获取图片或者文件)

来源:互联网 发布:linux 方向 编辑:程序博客网 时间:2024/06/15 20:54

SftpFileOper.java文件和SftpClientUtil.java文件配合使用吧,算是写好的公用方法,可以直接调用,需要的话可以直接粘贴使用。
算是已经写好的工具类了,当然网上也有很多讲解,这里是我自己的总结归纳。

操作sftp,首先要获取操作链接,因为最近一段时间一直在做这块的工作,对这块也是一个学习了吧。弥补了之前不会ftp操作的一点缺陷。以此为例,记录下来。


1.SftpFileOper.java文件

import java.io.FileOutputStream;
import java.io.InputStream;

public class SftpFileOper{

  //获取ftp链接
  public SftpClientUtil sftpConnection()throws Exception
  {
    String username = "huahua";//用户名huahua,可以在配置文件中获取
    String password = "huahuaPwd";//密码
    String host = "12.12.12.12";//ip地址
    int port = 3303;//端口号

    SftpClientUtil sftpClientUtil = new SftpClientUtil(host, port, username, password);
    sftpClientUtil.connect();
    return sftpClientUtil;
  }

  /**
   * 上传文件到ftp,参数含义:fileName:文件名称,inputstream:输入流,directory:ftp存储文件路径
   * 调用方法:SftpFileOper sftpFileOper = new SftpFileOper();
            FileMessage fileMessage = sftpFileOper.upSftpFileCommon(imgName, input, tarPath);
   */
  public FileMessage upSftpFileCommon(String fileName, InputStream inputstream, String directory)throws Exception
  {
    SftpClientUtil sftpClientUtil = sftpConnection();

    FileMessage fileMessage = sftpClientUtil.upload(directory, inputstream, fileName);
    inputstream.close();
    sftpClientUtil.disconnect();
    return fileMessage;
  }

  //下载ftp上的文件到本地
  public FileMessage downSftpFileCommon(String endFilePath, String directoryUrl, String fileName)
    throws Exception
  {
    SftpClientUtil sftpClientUtil = sftpConnection();
    FileMessage download = sftpClientUtil.download(directoryUrl, fileName);
    FileOutputStream fos = new FileOutputStream(endFilePath);
    byte[] b = new byte[10240];
    while (download.getInputStream().read(b, 0, 10240) != -1) {
      fos.write(b, 0, 10240);
    }
    fos.flush();
    fos.close();
    sftpClientUtil.disconnect();
    return download;
  }

  //删除ftp上,指定文件
  public void deleteSftpFileCommon(String directory, String deleteFile)
    throws Exception
  {
    SftpClientUtil sftpClientUtil = sftpConnection();
    sftpClientUtil.delete(directory, deleteFile);
    sftpClientUtil.disconnect();
  }

}

2.SftpClientUtil.java文件

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.ucfgroup.framework.utils.FileMessage;
import com.ucfgroup.framework.utils.SftpClientUtil;
import com.ucfgroup.framework.utils.SftpFileOper;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

public class SftpClientUtil{

  ChannelSftp sftp = null;

  private String host = "";

  private int port = 0;

  private String username = "";

  private String password = "";

  /**
   * 调用方式:
   * SftpClientUtil sftpclient = new SftpClientUtil( host,  port,  username, password);
   * sftpclient.connect();
   * sftpclient.download(fieDirPath,backup.getBackname(),strFileName);
   */
  //获取ftp链接
  public SftpClientUtil(String host, int port, String username, String password)
  {
    this.host = host;
    this.port = port;
    this.username = username;
    this.password = password;
  }

  //获取ftp链接
  public void connect()throws Exception{
    JSch jsch = new JSch();
    Session sshSession = jsch.getSession(this.username, this.host, this.port);
    this.logger.debug(SftpClientUtil.class + "Session created.");

    sshSession.setPassword(this.password);
    Properties sshConfig = new Properties();
    sshConfig.put("StrictHostKeyChecking", "no");
    sshSession.setConfig(sshConfig);
    sshSession.connect(20000);
    this.logger.debug(SftpClientUtil.class + " Session connected.");

    this.logger.debug(SftpClientUtil.class + " Opening Channel.");
    Channel channel = sshSession.openChannel("sftp");
    channel.connect();
    this.sftp = ((ChannelSftp)channel);
    this.logger.debug(SftpClientUtil.class + " Connected to " + this.host + ".");
  }
//断开ftp链接
  public void disconnect()throws Exception{
    if (this.sftp != null)
      if (this.sftp.isConnected())
        this.sftp.disconnect();
      else if (this.sftp.isClosed())
        this.logger.debug(SftpClientUtil.class + " sftp is closed already");
  }

  public FileMessage upload(String directory, InputStream is, String fileName)
  {
    if (!check(fileName))
      return new FileMessage("", Integer.valueOf(300), "传入参数不完全");
    FileMessage fileMessage;
    try {
      String endFileName = getNewFileName(fileName);
      try {
        Vector ls = this.sftp.ls(directory);
        if (null == ls)
          this.sftp.mkdir(directory);
      }
      catch (SftpException sftp) {
        this.sftp.mkdir(directory);
      }
      this.sftp.cd(directory);
      this.sftp.put(is, endFileName);
      fileMessage = new FileMessage(endFileName, Integer.valueOf(200), "操作成功");
    } catch (Exception e) {
      this.logger.error("上传文件失败", e);
      return new FileMessage(fileName, Integer.valueOf(500), "操作失败,出现异常");
    }
    return fileMessage;
  }

  public void uploadByDirectory(String directory)
    throws Exception
  {
    String uploadFile = "";
    List uploadFileList = listFiles(directory);
    Iterator it = uploadFileList.iterator();

    while (it.hasNext())
    {
      uploadFile = ((String)it.next()).toString();
      upload(directory, uploadFile);
    }
  }

  public void upload(String directory, String uploadFile)
    throws Exception
  {
    this.sftp.cd(directory);
    File file = new File(uploadFile);
    this.sftp.put(new FileInputStream(file), file.getName());
  }

  public void download(String directory, String downloadFile, String saveDirectory)
    throws Exception
  {
    String saveFile = saveDirectory + "//" + downloadFile;
    this.sftp.cd(directory);
    File file = new File(saveFile);
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    this.sftp.get(downloadFile, fileOutputStream);
    fileOutputStream.close();
    this.sftp.disconnect();
  }

  public FileMessage download(String directoryUrl, String fileName)
  {
    if (!check(fileName))
      return new FileMessage("", Integer.valueOf(300), "传入参数不完全");
    FileMessage fileMessage;
    try {
      this.sftp.cd(directoryUrl);
      InputStream is = this.sftp.get(fileName);
      fileMessage = new FileMessage(fileName, Integer.valueOf(200), "操作成功");
      fileMessage.setInputStream(is);
    } catch (Exception e) {
      this.logger.error("下载文件失败", e);
      return new FileMessage(fileName, Integer.valueOf(500), "操作失败,出现异常");
    }
    return fileMessage;
  }

  public FileMessage downloadFile(String directoryUrl, String fileName)
  {
    if (!check(fileName))
      return new FileMessage("", Integer.valueOf(300), "传入参数不完全");
    FileMessage fileMessage;
    try {
      this.sftp.cd(directoryUrl);
      InputStream is = this.sftp.get(fileName);
      fileMessage = new FileMessage(fileName, Integer.valueOf(200), "操作成功");
      byte[] bytes = getBytes(is);
      String imageBase64String = new BASE64Encoder().encode(bytes);
      fileMessage.setInputString(imageBase64String);
      is.close();
    } catch (Exception e) {
      this.logger.error("下载文件失败", e);
      return new FileMessage(fileName, Integer.valueOf(500), "操作失败,出现异常");
    }
    return fileMessage;
  }

  private byte[] getBytes(InputStream in)
  {
    byte[] buffer = null;
    try {
      ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
      byte[] b = new byte[1000];
      int n;
      while ((n = in.read(b)) != -1) {
        bos.write(b, 0, n);
      }
      in.close();
      bos.close();
      buffer = bos.toByteArray();
    }
    catch (IOException e) {
    }
    return buffer;
  }

  public void downloadByDirectory(String directory, String saveDirectory)
    throws Exception
  {
    String downloadFile = "";
    List downloadFileList = listFiles(directory);
    Iterator it = downloadFileList.iterator();

    while (it.hasNext())
    {
      downloadFile = ((String)it.next()).toString();
      if (downloadFile.toString().indexOf(".") < 0) {
        continue;
      }
      download(directory, downloadFile, saveDirectory);
    }
  }

  public void delete(String directory, String deleteFile)
    throws Exception
  {
    this.sftp.cd(directory);
    Vector content = this.sftp.ls(deleteFile);
    if (content != null)
      this.sftp.rm(deleteFile);
  }

  public List<String> listFiles(String directory)
    throws Exception
  {
    List fileNameList = new ArrayList();

    Vector fileList = this.sftp.ls(directory);
    Iterator it = fileList.iterator();

    while (it.hasNext())
    {
      String fileName = ((ChannelSftp.LsEntry)it.next()).getFilename();
      if ((".".equals(fileName)) || ("..".equals(fileName))) {
        continue;
      }
      fileNameList.add(fileName);
    }

    return fileNameList;
  }

  public void rename(String directory, String oldFileNm, String newFileNm)
    throws Exception
  {
    this.sftp.cd(directory);
    this.sftp.rename(oldFileNm, newFileNm);
  }

  public void cd(String directory) throws Exception {
    this.sftp.cd(directory);
  }
  public InputStream get(String directory) throws Exception {
    InputStream streatm = this.sftp.get(directory);
    return streatm;
  }

  private String getNewFileName(String fileName)
  {
    Long timeStamp = Long.valueOf(new Date().getTime());
    return timeStamp + "_" + fileName;
  }

  private boolean check(String fileName)
  {
    if (StringUtils.isBlank(this.host)) {
      return false;
    }
    if (StringUtils.isBlank(this.password)) {
      return false;
    }
    if (StringUtils.isBlank(this.username)) {
      return false;
    }
    if (this.port == 0) {
      return false;
    }

    return !StringUtils.isBlank(fileName);
  }

//测试方法
  public static void main(String[] args)
  {
    SftpClientUtil sftpClientUtil = new SftpClientUtil("127.0.0.1", 3303, "dly", "dlypwd");//ip、端口号、用户名、密码
    try {
      sftpClientUtil.connect();
      sftpClientUtil.delete("/home/love/", "2300打印机安装流程操作.docx");
      sftpClientUtil.upload("/home/love/filedic/", new FileInputStream(new File("D://huahua//文档//文档 操作说明.docx")), "文档 操作说明.docx");
      FileMessage download = sftpClientUtil.download("/home/love/filedic/文档 操作说明.docx", "文档 操作说明.docx");
      FileOutputStream fos = new FileOutputStream("D:/文档 操作说明.docx");
      byte[] b = new byte[10240];
      while (download.getInputStream().read(b, 0, 10240) != -1) {
        fos.write(b, 0, 10240);
      }
      fos.flush();

      sftpClientUtil.disconnect();
    }
    catch (Exception e)
    {
    }
  }
1 0
原创粉丝点击