Java常用文件操作-2
上篇文章记录了常用的文件操作,这里记录下通过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的更多相关文章
- Java常用文件操作-1
在我们的实际工作中经常会用到的文件操作,再此,将工作中碰到的做一个记录,以便日后查看. 1.复制文件夹到新文件夹下 /** * 复制文件夹下所有文件到指定路径 *@param oldPath *@pa ...
- java常见文件操作
收集整理的java常见文件操作,方便平时使用: //1.创建文件夹 //import java.io.*; File myFolderPath = new File(str1); try { if ( ...
- python 历险记(三)— python 的常用文件操作
目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...
- Python之常用文件操作
Python之常用文件操作
- Unix/Linux常用文件操作
Unix/Linux常用文件操作 秘籍:man命令是Unix/Linux中最常用的命令,因为命令行命令过多,我相信每个人都会经常忘记某些命令的用法,man命令就可以显示一个命令的所有选项,参数和说明, ...
- 真香!Python十大常用文件操作,轻松办公
日常对于批量处理文件的需求非常多,用Python写脚本可以非常方便地实现,但在这过程中难免会和文件打交道,第一次做会有很多文件的操作无从下手,只能找度娘. 本篇文章整理了10个Python中最常用到的 ...
- java中文件操作《一》
在日常的开发中我们经常会碰到对文件的操作,在java中对文件的操作都在java.io包下,这个包下的类有File.inputStream.outputStream.FileInputStream.Fi ...
- Java 基本文件操作
Java 文件操作 , 这也是基于Java API 操作来实现的. 文件是操作系统管理外存数据管理的基本单位, 几乎所有的操作系统都有文件管理机制. 所谓文件, 是具有符号名而且在逻辑上具有完整意义的 ...
- Java api 入门教程 之 JAVA的文件操作
I/O类使用 由于在IO操作中,需要使用的数据源有很多,作为一个IO技术的初学者,从读写文件开始学习IO技术是一个比较好的选择.因为文件是一种常见的数据源,而且读写文件也是程序员进行IO编程的一个基本 ...
随机推荐
- mysql时间戳与日期格式的相互转换
1.UNIX时间戳转换为日期用函数: FROM_UNIXTIME()[sql] view plain copyselect FROM_UNIXTIME(1156219870); 输出:2006-08- ...
- 用window的onload事件,窗体加载完毕的时候
<script type="text/javascript"> //用window的onload事件,窗体加载完毕的时候 window.onload=function( ...
- [leetcode-541-Reverse String II]
Given a string and an integer k, you need to reverse the first k characters for every 2k characters ...
- 【Android Developers Training】 4. 启动另一个Activity
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- web前端CSS2学习2017.6.17
CSS---表现层,修饰和表现html文档,为了解决结构层和表现层分离的问题. 通过CSS极大的提高了工作效率,方便工作人员维护和管理CSS:层叠样式表,目前用的最广泛的css版本为css2,最新版本 ...
- vue子父组件通信
之前在用vue写子父组件通信的时候,老是遇到问题!!! 子组件传值给父组件: 子组件:通过emit方法给父组件传值,这里的upparent是父组件要定义的方法 模板: <div v-on:cli ...
- centos7使用cobbler(2.8)批量部署操作系统之一
一. 批量部署操作系统的前提 要想批量部署操作系统,得具备以下条件: 客户机支持pxe网络引导 服务器端和客户端建立网络通信(DHCP) 服务器端要有可供客户机开机引导的引导文件 服务器端的可引 ...
- windows安装程序无法将windows配置为在此计算机的硬件上运行
关于装windows系统时,出现一些安装中断的处理 该方法适用于 windows安装程序无法将windows配置为在此计算机的硬件上运行 计算机意外地重新启动或遇到错误. Windows 安装无法继续 ...
- voa 2015 / 4 / 18
Words in This Story gerund - n. an English noun formed from a verb by adding -ing infinitive - n. th ...
- voa 2015 / 4 / 15
illustrated - v. to explain or decorate a story, book, etc., with pictures pediatrician – n. a docto ...