上篇文章记录了常用的文件操作,这里记录下通过SSH服务器操作Linux服务器的指定路径下的文件。

这里用到了第三方jar包 jsch-0.1.53.jar, jsch-api

1、删除服务器上指定路径下的所有文件(包括本目录)-经测试,在Linux下运行,没有问题

 /**
* 删除
*@param dst
*@param sftpUtil
*@return
*@author qin_hqing
*@date 2015年7月6日 下午4:45:31
*@comment
*/
protected static boolean removeFileFromSSH(String dst, ChannelSftp chanSftp) {
boolean bl = false; try {
chanSftp.cd(dst);
@SuppressWarnings("unchecked")
Vector<LsEntry> v = chanSftp.ls(dst);
if (v.size() == 2) { //空文件夹 直接删除
chanSftp.rmdir(dst);
}else {
int delSize = 0;
for (Iterator<LsEntry> iterator = v.iterator(); iterator.hasNext();) { LsEntry lsEntry = (LsEntry) iterator.next();
String ffName = lsEntry.getFilename();
if (ffName.indexOf(".")>0) { // file
chanSftp.rm(ffName); //删除文件
}else if(ffName.indexOf(".") == -1) {
removeFileFromSSH(dst+ffName+File.separator, chanSftp); //如果路径有问题可以试着把 File.separator 改成 "/"试试
chanSftp.cd(dst);
} if (delSize == v.size()-1) { //当前文件夹下还存在文件夹
removeFileFromSSH(dst, chanSftp);
}
delSize ++;
}
} bl = true;
} catch (SftpException e) {
e.printStackTrace();
} return bl;
}

2、上传文件到服务器

  A)这里我们用到了一个工具类,该工具类主要功能是通过SSH连接到Linux服务器,释放资源,在服务器上创建路径,代码如下:

 package fileUtil;

 import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException; /**
* @包名 util.sftp
* @文件名 SFTPChannelUtil.java
* @作者 Edi_Kai
* @创建日期 2015年7月3日
* @版本 V 1.0
* @描述
*/
public class SFTPChannelUtil { private static final Logger LOG = Logger.getLogger(SFTPChannelUtil.class); Session session = null;
Channel channel = null;
List<File> list = new ArrayList<File>(); private static SFTPChannelUtil util; public static SFTPChannelUtil getSftpChannelUtil() {
if (null == util) {
util = new SFTPChannelUtil();
}
return util;
} /**
* 获取ChannelSftp连接
*@param sftpDetails
*@param timeout
*@return
*@throws JSchException
*@author Edi_Kai
*@date 2015年7月3日 下午5:26:41
*@comment
*/
public ChannelSftp getChannel(Map<String, String> sftpDetails, int timeout)
throws JSchException { String ftpHost = sftpDetails.get(SFTPConstants.SFTP_REQ_HOST);
String ftpPort = sftpDetails.get(SFTPConstants.SFTP_REQ_PORT);
String ftpUserName = sftpDetails.get(SFTPConstants.SFTP_REQ_USERNAME);
String ftpPassword = sftpDetails.get(SFTPConstants.SFTP_REQ_PASSWORD); JSch jsch = new JSch(); // 创建JSch对象
session = jsch.getSession(ftpUserName, ftpHost, Integer.parseInt(ftpPort)); // 根据用户名,主机ip,端口获取一个Session对象
LOG.debug("Session created.");
if (ftpPassword != null) {
session.setPassword(ftpPassword); // 设置密码
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
LOG.debug("Session connected."); LOG.debug("Opening Channel.");
channel = session.openChannel("sftp"); // 打开SFTP通道
channel.connect(); // 建立SFTP通道的连接
LOG.debug("Connected successfully to ftpHost = " + ftpHost
+ ",as ftpUserName = " + ftpUserName + ", returning: "
+ channel);
return (ChannelSftp) channel;
} /**
* 关闭连接
*@throws Exception
*@author Edi_Kai
*@date 2015年7月3日 下午5:27:02
*@comment
*/
public void closeChannel() throws Exception {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
} /**
* 查看服务器上是否存在该目录,如果不存在则创建
*@param dir
*@param channelSftp
*@author Edi_Kai
*@date 2015年7月3日 下午5:07:25
*@comment
*/
public void createDir(String dir, ChannelSftp channelSftp) {
String parDir = dir.substring(0, dir.lastIndexOf("/"));
try {
Vector<?> content = channelSftp.ls(dir); if (content == null) {
createDir(parDir, channelSftp);
if (dir.indexOf(".")<0) {
channelSftp.mkdir(dir);
}
}
} catch (SftpException e) {
try {
createDir(parDir, channelSftp);//如果报异常,则说明dir路径不存在,则创建该路径
if (dir.indexOf(".")<0) {
channelSftp.mkdir(dir);
}
} catch (SftpException e1) {
e1.printStackTrace();
}
}
}
}

  该类中用到了一个存放常量参数的配置类,SFTPConstants.java,代码如下

package fileUtil;

import java.util.HashMap;
import java.util.Map; /**
* @包名 util.sftp
* @文件名 SFTPConstants.java
* @作者 Edi_Kai
* @创建日期 2015年7月3日
* @版本 V 1.0
* @描述
*/
public class SFTPConstants {
   public static final String SFTP_REQ_HOST = "host";
public static final String SFTP_REQ_PORT = "port";
public static final String SFTP_REQ_USERNAME = "username";
public static final String SFTP_REQ_PASSWORD = "password"; /**
* 获取Linux服务器 登录信息
*@return
*@author Edi_Kai
*@date 2015年7月3日 下午5:23:37
*@comment
*/
public static Map<String, String> getConfig() {
Map<String, String> cfg = new HashMap<String, String>();
cfg.put(SFTP_REQ_HOST, FileUtil.getPropValue("sshServerHost"));//192.168.1.110
cfg.put(SFTP_REQ_PORT, FileUtil.getPropValue("sshServerPort"));//
cfg.put(SFTP_REQ_USERNAME, FileUtil.getPropValue("sshServerUN"));
cfg.put(SFTP_REQ_PASSWORD, FileUtil.getPropValue("sshServerPwd")); return cfg;
}
}

  B)、上传文件到服务器

/**
* 将本服务器上的文件上传到SSH服务器的指定路径下
*@param src 本地服务器文件路径
*@param dst SSH服务器路径
*@return
*@author Edi_Kai
*@date 2015年7月6日 上午11:58:30
*@comment
*/
public static boolean upFile2SSHServer(String src, String dst) {
boolean bl = false;
SFTPChannelUtil util = SFTPChannelUtil.getSftpChannelUtil();
try {
ChannelSftp chanSftp = util.getChannel(SFTPConstants.getConfig(), 10000); List<File> list = FileUtil.getAllFile(src);
for (int i = 0; i < list.size(); i++) {
String path = list.get(i).getPath(); path = path.replaceAll("\\\\", "/");// E:/ad4/css/ad.css
if (path.indexOf(":")>-1) {
path = path.split(":")[1].substring(1);// ad4/css/ad.css
} util.createDir(dst, chanSftp); chanSftp.put(list.get(i).getPath(), serverPath);
} bl = true;
} catch (JSchException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
util.closeChannel();
} catch (Exception e) {
e.printStackTrace();
}
}
return bl;
}

如有遗漏,继续追加....

/**************************************************************/

  每天多学一点....

/**************************************************************/

Java常用文件操作-2的更多相关文章

  1. Java常用文件操作-1

    在我们的实际工作中经常会用到的文件操作,再此,将工作中碰到的做一个记录,以便日后查看. 1.复制文件夹到新文件夹下 /** * 复制文件夹下所有文件到指定路径 *@param oldPath *@pa ...

  2. java常见文件操作

    收集整理的java常见文件操作,方便平时使用: //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if ( ...

  3. python 历险记(三)— python 的常用文件操作

    目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...

  4. Python之常用文件操作

    Python之常用文件操作

  5. Unix/Linux常用文件操作

    Unix/Linux常用文件操作 秘籍:man命令是Unix/Linux中最常用的命令,因为命令行命令过多,我相信每个人都会经常忘记某些命令的用法,man命令就可以显示一个命令的所有选项,参数和说明, ...

  6. 真香!Python十大常用文件操作,轻松办公

    日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘. 本篇文章整理了10个Python中最常用到的 ...

  7. java中文件操作《一》

    在日常的开发中我们经常会碰到对文件的操作,在java中对文件的操作都在java.io包下,这个包下的类有File.inputStream.outputStream.FileInputStream.Fi ...

  8. Java 基本文件操作

    Java 文件操作 , 这也是基于Java API 操作来实现的. 文件是操作系统管理外存数据管理的基本单位, 几乎所有的操作系统都有文件管理机制. 所谓文件, 是具有符号名而且在逻辑上具有完整意义的 ...

  9. Java api 入门教程 之 JAVA的文件操作

    I/O类使用 由于在IO操作中,需要使用的数据源有很多,作为一个IO技术的初学者,从读写文件开始学习IO技术是一个比较好的选择.因为文件是一种常见的数据源,而且读写文件也是程序员进行IO编程的一个基本 ...

随机推荐

  1. mysql in 和 not in 语句用法

    1.mysql in语句 select * from tb_name where id in (10,12,15,16);2.mysql not in 语句 select * from tb_name ...

  2. Selenium chrome配置代理Python版

    环境: windows 7 + Python 3.5.2 + Selenium 3.4.2 + Chrome Driver 2.29 + Chrome 58.0.3029.110 (64-bit) S ...

  3. [leetcode-605-Can Place Flowers]

    Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, ...

  4. SmartSql漫谈

    最近在看smartSql源码,兄弟写的.写的很不错取取经. 记录下一些学习的东西,刚开始我先不系统的写了,随意一点哈,我看的差不多再给大家一个模块一个模块系统的写. public T ExecuteS ...

  5. Linux文件属性上

    文件属性概述(ls -lhi) linux里一切皆文件Linux系统中的文件或目录的属性主要包括:索引节点(inode),文件类型,权限属性,链接数,所归属的用户和用户组,最近修改时间等内容: 解释: ...

  6. Tornado+MySQL模拟SQL注入

    实验环境: python 3.6 + Tornado 4.5 + MySQL 5.7 实验目的: 简单模拟SQL注入,实现非法用户的成功登录 一.搭建环境 1.服务端的tornado主程序app.py ...

  7. KBEngine简单RPG-Demo源码解析(3)

    十四:在世界中投放NPC/MonsterSpace的cell创建完毕之后, 引擎会调用base上的Space实体, 告知已经获得了cell(onGetCell),那么我们确认cell部分创建好了之后就 ...

  8. tomcat+jdk+mysql

    转自 http://www.cnblogs.com/liulinghua90/ ,写的很详细,转来共享私藏 按照下面的步骤一步一步来搭建tomcat+jdk+mysql环境.   [Linux环境]- ...

  9. TOJ4114(活用树状数组)

    TOJ指天津大学onlinejudge 题意:给你由N个数组成的数列,算出它们的所有连续和的异或和,比如:数列{1,2},则answer = 1 ^ 2 ^ (1 + 2) = 0. 这道题有几个关键 ...

  10. visual Studio 2017 扩展开发(一)《向Visual Studio菜单栏新增一个菜单》

    最近有接触到关于visual studio 2017 扩展的开发,特此记录,也是为了督促自己去深入了解其原理. 开始开发Visual Studio 扩展,在这里我安装了visual studio 20 ...