update
This commit is contained in:
87
src/main/java/com/yutou/tools/utils/SFTPTools.java
Normal file
87
src/main/java/com/yutou/tools/utils/SFTPTools.java
Normal file
@@ -0,0 +1,87 @@
|
||||
package com.yutou.tools.utils;
|
||||
|
||||
import com.jcraft.jsch.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ListIterator;
|
||||
import java.util.Properties;
|
||||
|
||||
public class SFTPTools {
|
||||
Session sshSession = null;
|
||||
ChannelSftp sftp = null;
|
||||
|
||||
public SFTPTools() throws Exception {
|
||||
JSch jsch = new JSch();
|
||||
sshSession = jsch.getSession("yutou", "113.65.152.143", 23);
|
||||
sshSession.setPassword("34864394");
|
||||
Properties sshConfig = new Properties();
|
||||
sshConfig.put("StrictHostKeyChecking", "no");
|
||||
sshSession.setConfig(sshConfig);
|
||||
sshSession.connect();
|
||||
Channel channel = sshSession.openChannel("sftp");
|
||||
channel.connect();
|
||||
sftp = (ChannelSftp) channel;
|
||||
}
|
||||
/**
|
||||
* 删除
|
||||
*/
|
||||
public void delete(String directory, String deleteFile) {
|
||||
try {
|
||||
sftp.cd(directory);
|
||||
sftp.rm(deleteFile);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 上传
|
||||
*/
|
||||
public void upload(String directory, String uploadFile) {
|
||||
try {
|
||||
sftp.cd(directory);
|
||||
File file = new File(uploadFile);
|
||||
sftp.put(new FileInputStream(file), file.getName());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 下载
|
||||
*/
|
||||
public void download(String directory, String downloadFile, String saveFile) {
|
||||
try {
|
||||
sftp.cd(directory);
|
||||
File file = new File(saveFile);
|
||||
sftp.get(downloadFile, new FileOutputStream(file));//可以用流
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
//https://www.cnblogs.com/nlpvv/articles/11244553.html
|
||||
public void getPath() {
|
||||
try {
|
||||
sftp.cd("/home");
|
||||
ListIterator listIterator=sftp.ls("/media/yutou/4t/public/").listIterator();
|
||||
while (listIterator.hasNext()){
|
||||
ChannelSftp.LsEntry entry= (ChannelSftp.LsEntry) listIterator.next();
|
||||
System.out.println(entry.getFilename()+" ="+entry.getAttrs().getSize());
|
||||
}
|
||||
sftp.disconnect();
|
||||
} catch (SftpException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
SFTPTools tools=new SFTPTools();
|
||||
tools.getPath();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user