服务器文件操作 ChannelSftp 的用法
put(): 文件上传get(): 文件下载cd(): 进入指定目录ls(): 得到指定目录下的文件列表rm(): 删除指定文件。
1.常用方法
put(): 文件上传
get(): 文件下载
cd(): 进入指定目录
ls(): 得到指定目录下的文件列表
rm(): 删除指定文件
2.java案例
package com.test01;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
/**
-
〈一句话功能简述〉
-
〈〉
-
@author Min.Z
-
@create 2021/4/21
-
@since 1.0.0
*/
public class testend {
private static final int connectTimeout = 30000;public static void main(String[] args) {
//文件名
String fileName = “zhoumin.txt”;
//服务器文件路径
String path = “/min/ap/ecsp/”;
//服务器ip
String host = “192.168.43.218”;
//服务器端口号
int port = 22;
//服务器登录用户名
String user = “min”;
//服务器用户密码
String password = “123”;
//要保存的文件:路径+名字
String saveLocalFile = “D:\abc.txt”;
//要生成本地的文件:路径+名字
String createLocalFile = “D:\zhou123.txt”;
//要删除本地的文件的路径
String localPath = “D:\Temp\”;/** * 读取文件内容返回byte数组 */ byte[] array = download(fileName, path, host, port, user, password); try { //将文件的byte的数组转为String类型, System.out.println(new String(array, "utf-8")); } catch (Exception e) { throw new RuntimeException(e); } /** * 下载文件到本地 */ boolean fileExist = downloadLocal(saveLocalFile, fileName, path, host, port, user, password); System.out.println("文件是否存在=="+fileExist); //读取下载后的本地文件 if (fileExist) { readLocalFile(saveLocalFile); } //创建并写入本地文件 File file = writeLocalFile(createLocalFile); /** * 上传文件到服务器 */ uploadLocalFile(file, path, host, port, user, password); /** * 根据文件创建时间删除文件 */ try { Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-04-21 16:20:00"); //删除本地文件 deleteLocalFile(localPath, date); removeDateFile(date, path, host, port, user, password); } catch (ParseException e) { e.printStackTrace(); }
}
public static boolean stringIsNotEmpty(String str) {
return null != str && str.length() != 0;
}/**
-
@return 读取文件内容返回byte数组
*/
public static byte[] download(String fileName, String path, String host, int port, String user, String password) {
Session session = null;
ChannelSftp channel = null;//ChannelSftp类是JSch实现SFTP核心类
try {
JSch jsch = new JSch();
if (port == 0) {
session = jsch.getSession(user, host);
} else {
session = jsch.getSession(user, host, port);
}
session.setPassword(password);
//禁用StrictHostKeyChecking选项会使连接的安全性低于启用该选项的安全性,
// 因为它可以让您连接到远程服务器而无需验证其SSH主机密钥.如果启用该选项,
// 则只能连接到SSH客户端已知密钥的服务器
session.setConfig(“StrictHostKeyChecking”, “no”);
session.connect(connectTimeout);
channel = (ChannelSftp) session.openChannel(“sftp”);
channel.connect(connectTimeout);if (!(path == null || path.trim().length() == 0)) { channel.cd(path);//进入指定目录 } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); channel.get(fileName, outputStream);//文件下载,文件不存在报错 2: No such file byte[] arrayOfByte = outputStream.toByteArray(); return arrayOfByte;
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {//2: No such file
// file doesn’t exist
throw new RuntimeException(fileName+“文件不存在”);
} else {
throw new RuntimeException(e);//这个一定要捕捉异常,不然代码报错,为没有返回值
}
} catch (Exception e0) {
throw new RuntimeException(e0);
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
/**
-
下载文件到本地
-
@saveLocalFile 保存到本地的文件 路径+文件名
-
@return 是否存在文件
*/
public static boolean downloadLocal(String saveLocalFile, String fileName, String path, String host, int port, String user, String password) {
Session session = null;
ChannelSftp channel = null;
boolean fileExist = true;//文件存在
try {
JSch jsch = new JSch();
if (port == 0) {
session = jsch.getSession(user, host);
} else {
session = jsch.getSession(user, host, port);
}
session.setPassword(password);
session.setConfig(“StrictHostKeyChecking”, “no”);
session.connect(connectTimeout);
channel = (ChannelSftp) session.openChannel(“sftp”);
channel.connect(connectTimeout);if (!(path == null || path.trim().length() == 0)) { channel.cd(path);//进入指定目录 } File file = new File(saveLocalFile); if (file.exists()) { file.delete(); } FileOutputStream fos = new FileOutputStream(file); channel.get(fileName,fos);//get()文件下载,文件不存在时会报错
} catch (SftpException e) {
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {//2: No such file
fileExist = false;
} else {
throw new RuntimeException(e);//这个一定要捕捉异常,不然代码报错,为没有返回值
}
} catch (Exception e0) {
throw new RuntimeException(e0);
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
return fileExist;
}
}
/**
- 读取本地文件
- @param saveLocalFile 文件路径+文件名
*/
public static void readLocalFile(String saveLocalFile) {
File file = new File(saveLocalFile);
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while (stringIsNotEmpty(line = br.readLine())) {//一行一行的读取
System.err.println(line);
}
fis.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
-
创建并写入本地文件
-
@param createLocalFile 文件路径+文件名
*/
public static File writeLocalFile(String createLocalFile) {
File file = new File(createLocalFile);
try {
//①设置编码方式
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), “GBK”));//②不设置编码方式 BufferedWriter bw = new BufferedWriter(new FileWriter(file, true)); bw.write("我是java"); bw.newLine();//换行,在不同的系统中会展示不同的符号,如果在Linux上不要读取到^M,则不应使用这种换行方式,直接在字符后面接\n bw.write("哇,哇哇"); bw.newLine(); bw.write("结束来了来了"); bw.flush();//刷新缓冲流,把数据写进该文件。如果存在for循环,一定要在for循环里添加bw.flush() bw.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
/**
- 按条件删除本地文件
- @param localPath 文件路径
*/
public static void deleteLocalFile(String localPath,Date date) {
File file = new File(localPath);
for (String fileName : file.list()) {
try {
String pfile = localPath + fileName;//当前文件完整路径
FileTime fileTime = Files.readAttributes(Paths.get(pfile), BasicFileAttributes.class).creationTime();//文件创建时间
if (fileTime.toMillis() < date.getTime()) {//date大于创建时间
File f = new File(pfile);
if (!f.isDirectory()) {//非文件夹
System.out.println(“删除文件===”+fileName);
f.delete();//文件删除
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
-
上传文件到服务器
*/
public static void uploadLocalFile(File file, String path, String host, int port, String user, String password) {
Session session = null;
ChannelSftp channel = null;
try {
JSch jsch = new JSch();
if (port == 0) {
session = jsch.getSession(user, host);
} else {
session = jsch.getSession(user, host, port);
}
session.setPassword(password);
session.setConfig(“StrictHostKeyChecking”, “no”);
session.connect(connectTimeout);
channel = (ChannelSftp) session.openChannel(“sftp”);
channel.connect(connectTimeout);if (!(path == null || path.trim().length() == 0)) { channel.cd(path);//进入指定目录 } InputStream is = new FileInputStream(file); channel.put(is, file.getName()); is.close();
} catch (Exception e0) {
throw new RuntimeException(e0);
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
/**
-
根据时间删除服务器上的文件
*/
public static void removeDateFile(Date date, String path, String host, int port, String user, String password) {
Session session = null;
ChannelSftp channel = null;
Vector vector = null;
try {
JSch jsch = new JSch();
if (port == 0) {
session = jsch.getSession(user, host);
} else {
session = jsch.getSession(user, host, port);
}
session.setPassword(password);
session.setConfig(“StrictHostKeyChecking”, “no”);
session.connect(connectTimeout);
channel = (ChannelSftp) session.openChannel(“sftp”);
channel.connect(connectTimeout);if (!(path == null || path.trim().length() == 0)) { channel.cd(path);//进入指定目录 vector = channel.ls(path);//获取文件目录下所有的文件 } for (Object item : vector) { ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) item; if (!entry.getAttrs().isDir()) { String fileName = entry.getFilename(); if (".".equals(fileName) || "..".equals(fileName)) { continue; } Date date1 = new Date(entry.getAttrs().getMTime() * 1000L); if (date1.getTime() < date.getTime()) { channel.rm(path + fileName); } } }
} catch (Exception e0) {
throw new RuntimeException(e0);
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}
-
更多推荐
所有评论(0)