Skip to content

Instantly share code, notes, and snippets.

@HydrangeaPurple
Created August 4, 2021 08:58
Show Gist options
  • Select an option

  • Save HydrangeaPurple/b0824223fc02a3abf36af1d6e7c99c27 to your computer and use it in GitHub Desktop.

Select an option

Save HydrangeaPurple/b0824223fc02a3abf36af1d6e7c99c27 to your computer and use it in GitHub Desktop.
java sftp 下载上传文件
import org.apache.commons.codec.binary.Hex;
import java.io.*;
import java.security.MessageDigest;
import java.util.*;
public class FilesUtil {
/**
*
* Description:得到带后缀的路径……
*
* @param url
* @return
*/
public static String getUrl(String url) {
if (!url.endsWith("/")) {
url = url + "/";
}
return url;
}
/**
*
* Description:得到带后缀的路径……
*
* @param url
* @return
*/
public static String getNoUrl(String url) {
if (url.endsWith("/")) {
url = url.substring(0, url.length() - 1);
}
return url;
}
/**
*
* Description:创建文件夹……
*
* @param path
*/
public static boolean createDir(String path) {
path = path.replace("\\", "/");
if (!path.endsWith("/")) {
path = path + "/";
}
int start = path.indexOf("/");
String pPath = "";
while (start >= 0) {
pPath = path.substring(0, start);
File dir = new File(pPath);
if (!dir.exists()) {
dir.mkdir();
}
start = path.indexOf("/", start + 1);
}
return true;
}
/**
*
* Description:不存在则创建文件……
*
* @param fileName
* @throws IOException
*/
public static boolean createFile(String fileName) {
fileName = fileName.replace("\\", "/");
int start = fileName.lastIndexOf("/");
String path = fileName.substring(0, start);
FilesUtil.createDir(path);
File file = new File(fileName);
if (!file.exists()) {
try {
return file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
/**
*
* Description:删除文件……
*
* @param fileName
* @return
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists()) {
file.delete();
}
return true;
}
/**
*
* Description:删除文件夹……
*
* @param filePath
* @return
*/
public static boolean delDir(String filePath) {
File dir = new File(filePath);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = delDir(dir + "/" + children[i]);
if (!success) {
return false;
}
}
}
if (dir.delete()) {
return true;
}
return false;
}
/**
*
* Description:检测文件/文件夹是否存在……
*
* @param filePath
* @return
*/
public static boolean checkFile(String filePath) {
File dir = new File(filePath);
return dir.exists();
}
/**
*
* Description:不存在则写文件……
*
* @param fileName
* @param fileContent
* @return
*/
public static boolean writeFileNotExist(String fileName, String fileContent) {
if (FilesUtil.checkFile(fileName)) {
return false;
}
FilesUtil.createFile(fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName, true);
out.write(fileContent.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* Description:强制重写文件……
*
* @param fileName
* @param fileContent
* @return
*/
public static boolean writeFile(String fileName, String fileContent) {
FilesUtil.deleteFile(fileName);
FilesUtil.createFile(fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName, true);
out.write(fileContent.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* Description:追加写文件……
*
* @param fileName
* @param fileContent
* @return
*/
public static boolean writeAppendFile(String fileName, String fileContent) {
FilesUtil.createFile(fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(fileName, true);
out.write(fileContent.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
if (null != out) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* Description:重命名文件……
*
* @param fileName
* @param nFileName
* @return
*/
public static boolean renameFile(String fileName, String nFileName) {
File file = new File(fileName);
file.renameTo(new File(nFileName));
return true;
}
/**
*
* Description:读取子文件夹并排序……
*
* @param path
* @return
*/
public static String[] readChirList(String path) {
if (!FilesUtil.checkFile(path)) {
return null;
}
File dir = new File(path);
File[] files = dir.listFiles();
if (null == files || files.length <= 0) {
return null;
}
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
@Override
public boolean equals(Object obj) {
return true;
}
});
String[] list = new String[files.length];
for (int i = 0; i < list.length; i++) {
list[i] = files[i].getName();
}
return list;
}
/**
*
* Description:按行读文件[最大为10000行]……
*
* @param fileName
* @return
*/
public static String readFileByLines(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
return null;
}
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
sb.append(tempString).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return sb.toString();
}
/**
*
* Description:按行读文件+返回列表……
*
* @param fileName
* @return
*/
public static List<String> readFileByList(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
return null;
}
BufferedReader reader = null;
List<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
list.add(tempString);
;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return list;
}
/**
*
* Description:文件平台转换,比如.sh文件……
*
* @param content
* @return
*/
public static String winString2Linux(final String content) {
if (null == content || "".equals(content)) {
return null;
}
StringBuffer buffer = new StringBuffer();
final char[] chars = content.toCharArray();
char curChar;
for (int i = 0; i < chars.length; i++) {
curChar = chars[i];
if ('\r' != curChar) {
buffer.append(curChar);
}
}
return buffer.toString();
}
/**
* 复制文件
*
* @param source
* @param target
*/
public static void copyFile(String source, String target) {
FileInputStream fin = null;
FileOutputStream fout = null;
try {
File s = new File(source);
File t = new File(target);
fin = new FileInputStream(s);
fout = new FileOutputStream(t);
byte[] a = new byte[1024 * 1024 * 4];
int b = -1;
// 边读边写
while ((b = fin.read(a)) != -1) {
fout.write(a, 0, b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fout) {
fout.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (null != fin) {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 复制文件或者文件夹
*
* @param source
* @param target
*/
public static void copy(String source, String target) {
// 获取目录下所有文件
File f = new File(source);
File[] allf = f.listFiles();
if (f.isDirectory()) {
FilesUtil.createDir(target);
} else {
FilesUtil.copyFile(source, target);
return;
}
// 遍历所有文件
for (File fi : allf) {
try {
// 拼接目标位置
String URL = target + fi.getAbsolutePath().substring(source.length());
// 创建目录或文件
if (fi.isDirectory()) {
FilesUtil.createDir(URL);
} else {
FilesUtil.copyFile(fi.getAbsolutePath(), URL);
}
if (fi.isDirectory()) {
copy(fi.getAbsolutePath(), URL);
}
} catch (Exception e) {
System.out.println("error");
}
}
}
/**
*
* Description:判断文件是否为二进制……
*
* @param path
* @return
*/
public static boolean isBinary(String path) {
boolean isBinary = false;
FileInputStream fin = null;
try {
File file = new File(path);
fin = new FileInputStream(file);
long len = file.length();
for (int j = 0; j < (int) len; j++) {
int t = fin.read();
if (t < 32 && t != 9 && t != 10 && t != 13) {
isBinary = true;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return isBinary;
}
public static long readAllFilesSize(File dir, long sum) {
try {
if (dir.isFile()) {
return sum + dir.length();
}
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
sum += readAllFilesSize(files[i], sum);
} else {
sum += files[i].length();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sum;
}
public static void listFile(String fileDir, List<Map<String, String>> fileList, int level) {
File file = new File(fileDir);
File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
if (files == null) {// 如果目录为空,直接退出
return;
}
String str = "";
for (int i = 0; i < level; i++) {
str += "  ";
}
// 遍历,目录下的所有文件
for (File f : files) {
Map<String, String> map = new HashMap<String, String>();
if (f.isFile()) {
map.put("fileName", str + "文件名 :" + f.getName() + " 大小: " + f.length() + " 时间:"
+ BusDateUtils.geFormatTime(f.lastModified()));
map.put("dir", fileDir + f.getName());
map.put("name", f.getName());
fileList.add(map);
} else if (f.isDirectory()) {
map.put("fileName", str + "文件名 :" + f.getName());
map.put("dir", "");
fileList.add(map);
listFile(f.getAbsolutePath(), fileList, ++level);
}
}
}
/**
* 计算文件折MD5值
*/
public static String getMD5(File file) {
FileInputStream fileInputStream = null;
try {
MessageDigest MD5 = MessageDigest.getInstance("MD5");
fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
MD5.update(buffer, 0, length);
}
return new String(Hex.encodeHex(MD5.digest()));
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void listTopFiles(String fileDir, List<Map<String, String>> fileList) {
File file = new File(fileDir);
File[] files = file.listFiles();// 获取目录下的所有文件或文件夹
if (files == null) {// 如果目录为空,直接退出
return;
}
// 遍历,目录下的所有文件
for (File f : files) {
Map<String, String> map = new HashMap<String, String>();
if (f.isFile()) {
map.put("fileName", "文件名 :" + f.getName() + " 大小: " + f.length() + " 时间:"
+ BusDateUtils.geFormatTime(f.lastModified()));
// map.put("dir", fileDir + f.getName());
// map.put("name", f.getName());
fileList.add(map);
} else if (f.isDirectory()) {
}
}
}
public static void main(String[] args) {
String src = "C:/kaoqin/1.jpg";
String target = "C:/kaoqin/microMsg." + (System.currentTimeMillis()) + ".jpg";
FilesUtil.copy(src, target);
}
}
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import java.io.IOException;
/**
* // https://mvnrepository.com/artifact/com.hierynomus/sshj
* implementation group: 'com.hierynomus', name: 'sshj', version: '0.31.0'
*
* @author chengyiqun
* @version V1.0
* @date 2021/8/4 10:56
*/
public class MySftpClient implements AutoCloseable {
private String hostname;
private int port;
private String username;
private String password;
private final SSHClient ssh;
public MySftpClient(String hostname, String username, String password) throws IOException {
this(hostname, 22, username, password);
}
public MySftpClient(String hostname, int port, String username, String password) throws IOException {
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.ssh = new SSHClient();
this.connect();
}
private void connect() throws IOException {
// ssh.loadKnownHosts(); to skip host verification
this.ssh.addHostKeyVerifier(new PromiscuousVerifier());
this.ssh.connect(this.hostname, this.port);
this.ssh.authPassword(this.username, this.password);
}
/**
* @param source 服务器路径
* @param dest 路径
* @throws IOException
*/
public void downloadFile(String source, String dest) throws IOException {
FilesUtil.createFile(dest);
SFTPClient sftp = this.ssh.newSFTPClient();
try {
sftp.get(source, dest);
} finally {
try {
sftp.close();
} catch (IOException ignored) { }
}
}
/**
* @param source 本地路径
* @param dest 服务器路径
* @throws IOException
*/
public void uploadFile(String source, String dest) throws IOException {
SFTPClient sftp = this.ssh.newSFTPClient();
try {
dest = dest.replace("\\", "/");
String folderPath = dest.substring(0, dest.lastIndexOf("/"));
if (!ObjectIsNull.check(folderPath)) {
sftp.mkdirs(folderPath);
}
sftp.put(source, dest);
} finally {
try {
sftp.close();
} catch (IOException ignored) {
}
}
}
/**
* 校验sftp文件是否存在
*
* @param dest 服务器路径
* @return
* @throws IOException
*/
public boolean checkFile(String dest) throws IOException {
SFTPClient sftp = this.ssh.newSFTPClient();
try {
return sftp.size(dest) >= 0;
} finally {
try {
sftp.close();
} catch (IOException ignored) {
}
}
}
@Override
public void close() {
if (this.ssh != null && this.ssh.isConnected()) {
try {
this.ssh.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
// 下载
// try (MySftpClient sftp = new MySftpClient("localhost", "cyq", "123456")) {
// sftp.downloadFile("test.txt", "R:\\www\\test.txt");
// }
// 上传
// try (MySftpClient sftp = new MySftpClient("localhost", "cyq", "123456")) {
// sftp.uploadFile("R:\\www\\haha.txt", "\\haha\\haha1.txt");
// }
// 校验存在
// try (MySftpClient sftp = new MySftpClient("localhost", "cyq", "123456")) {
// sftp.checkFile("haha.txt");
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment