JAVA 上传文件到linux上并解压缩
package com.inborn.inshop.controller.mkt;
import java.io.*;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Created by ck on 2017/3/8.
*/
public class FileUpAndUncompress {
/**
* 文件上传
*/
public static void fileUploadByFtp(){
File imagefile = new File("D:\\logo.zip");
String imagefileFileName = "logo.zip";
//创建ftp客户端
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("GBK");
String hostname = "192.168.1.57";
int port = 21;
String username = "root";
String password = "inborn@57";
try {
//链接ftp服务器
ftpClient.connect(hostname, port);
//登录ftp
ftpClient.login(username, password);
ftpClient.setDataTimeout(60000); //设置传输超时时间为60秒
ftpClient.setConnectTimeout(60000); //连接超时为60秒
int reply = ftpClient.getReplyCode();
System.out.println(reply);
//如果reply返回230就算成功了,如果返回530密码用户名错误或当前用户无权限下面有详细的解释。
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return ;
}
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.makeDirectory("path");//在root目录下创建文件夹
// String remoteFileName = System.currentTimeMillis()+"_"+imagefileFileName;
InputStream input = new FileInputStream(imagefile);
ftpClient.storeFile(imagefileFileName, input);//文件你若是不指定就会上传到root目录下
input.close();
ftpClient.logout();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (ftpClient.isConnected())
{
try
{
ftpClient.disconnect();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
/**
* 解压zip文件
* @param sourceFile,待解压的zip文件; toFolder,解压后的存放路径
* @throws Exception
**/
public static void zipToFile(String sourceFile, String toFolder) throws Exception {
String toDisk = toFolder;//接收解压后的存放路径
ZipFile zfile = new ZipFile(sourceFile);//连接待解压文件
System.out.println("要解压的文件是:"+ zfile.getName());
Enumeration zList = zfile.entries();//得到zip包里的所有元素
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
System.out.println("打开zip文件里的文件夹:"+ ze.getName() +"skipped...");
continue;
}
System.out.println("zip包里的文件:"+ ze.getName() +" "+"大小为:" + ze.getSize() +"KB");
//以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(getRealFileName(toDisk, ze.getName())));
InputStream inputStream = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, readLen);
}
inputStream.close();
outputStream.close();
System.out.println("已经解压出:"+ ze.getName());
}
zfile.close();
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
* @param zippath 指定根目录
* @param absFileName 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String zippath, String absFileName){
String[] dirs = absFileName.split("/", absFileName.length());
File ret = new File(zippath);// 创建文件对象
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {// 检测文件是否存在
ret.mkdirs();// 创建此抽象路径名指定的目录
}
ret = new File(ret, dirs[dirs.length - 1]);// 根据 ret 抽象路径名和 child 路径名字符串创建一个新 File 实例
return ret;
}
/**
* 远程解压zip文件
*/
public static void remoteZipToFile(){
try {
Connection connection = new Connection("192.168.1.57");// 创建一个连接实例
connection.connect();// Now connect
boolean isAuthenticated = connection.authenticateWithPassword("root", "inborn@57");// Authenticate
if (isAuthenticated == false)throw new IOException("user and password error");
Session sess = connection.openSession();// Create a session
System.out.println("start exec command.......");
sess.requestPTY("bash");
sess.startShell();
InputStream stdout = new StreamGobbler(sess.getStdout());
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
PrintWriter out = new PrintWriter(sess.getStdin());
out.println("cd /root/");
out.println("ll");
out.println("unzip -o -d /root/path logo.zip");
out.println("ll");
out.println("exit");
out.close();
sess.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF | ChannelCondition.EXIT_STATUS,30000);
System.out.println("下面是从stdout输出:");
while (true) {
String line = stdoutReader.readLine();
if (line == null)break;
System.out.println(line);
}
System.out.println("下面是从stderr输出:");
while (true) {
String line = stderrReader.readLine();
if (line == null)break;
System.out.println(line);
}
System.out.println("ExitCode: " + sess.getExitStatus());
sess.close();/* Close this session */
connection.close();/* Close the connection */
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
}
public static void main(String[] args) throws Exception {
//fileUploadByFtp();
// zipToFile("D:\\logo.zip","D:\\webstorm");
remoteZipToFile();
}
}
依赖包:
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>ch.ethz.ganymed</groupId>
<artifactId>ganymed-ssh2</artifactId>
<version>build210</version>
</dependency>
JAVA 上传文件到linux上并解压缩的更多相关文章
- SpringBoot 上传文件到linux服务器 异常java.io.FileNotFoundException: /tmp/tomcat.50898……解决方案
SpringBoot 上传文件到linux服务器报错java.io.FileNotFoundException: /tmp/tomcat.50898-- 报错原因: 解决方法 java.io.IOEx ...
- windows上传文件到 linux的hdfs
一.windows上传文件到 linux的hdfs 1.先在 centos 上开启 hdfs, 用 jps 可以看到下面信息, 说明完成开启 2.在win上配置 hadoop (https://www ...
- 使用putty上传文件到linux系统
使用window的cmd命令 上传文件到linux 使用putty下的 pscp.exe pscp -r -l root -pw 1234567890 e:/htk 192.168.0.204:/r ...
- Windows上传文件到linux 使用winscp
Windows上传文件到linux 使用winscp, winscp下载目录 https://sourceforge.net/projects/winscp/postdownload?source=d ...
- XShell本地上传文件到Ubuntu上及从Ubuntu下载文件到本地
使用XShell本地上传文件到Ubuntu上及从Ubuntu下载文件到本地. 1.第一种方法是最常用的 :如果下载了Xshell和Xftp,Ctrl+Alt+F就可以选择文件的互传了!(虚拟机/云服务 ...
- 用winscp从本地上传文件到服务器上出现复制文件到远端时错误。
用winscp从本地上传文件到服务器上出现复制文件到远端时错误. 错误码:4 服务器返回的错误消息:write failed 报错如下图所示: 分析过程: 1.刚开始以为是权限不够,后面上网查了一下是 ...
- Git学习笔记——从一台电脑上传文件到Github上
目标:从一台电脑上传文件到Github上 前提: 1.这里假定已在Github上创建了仓库,建立了仓库 2.已在这台电脑上安装了Git客户端 实验环境: 1.Windows 10 64位,已安装了Gi ...
- java使用JSCH连接FTP(Linux服务器)上传文件到Linux服务器
首先需要用到jsch-0.1.54.jar 包: 链接: https://pan.baidu.com/s/1kZR6MqwpCYht9Pp_D6NKQw 密码: gywx 直接上代码: package ...
- 用sftp上传文件至linux服务器
1.项目环境 框架:springmvc 项目管理工具:maven 2.必须使用的jar com.jcraft jsch 0.1.27 test 3.新建一个FileUpDown工具类,在类中添加 ...
随机推荐
- 创建 .m2 文件夹
首次使用 Maven 创建 .m2 文件夹 1. cmd2. mvn help:system
- eclipse 安装和使用AmaterasUML
1. 安装AmaterasUML前,需要先安装GEF(Eclipse Graphical Editing Framework (GEF)) 采用eclipse在线安装方式安装就好. a. 查看ecli ...
- 设计模式之Strategy(策略)(转)
Strategy是属于设计模式中 对象行为型模式,主要是定义一系列的算法,把这些算法一个个封装成单独的类. Stratrgy应用比较广泛,比如, 公司经营业务变化图, 可能有两种实现方式,一个是线条曲 ...
- linux常用命令:mv 命令
mv命令是move的缩写,可以用来移动文件或者将文件改名(move (rename) files),是Linux系统下常用的命令,经常用来备份文件或者目录. 1.命令格式: mv [选项] 源文件或目 ...
- Numpy 数组简单操作
创建一个2*2的数组,计算对角线上元素的和 import numpy as np a = np.arange(4).reshape(2,2) print (a) #[[0 1] # [2 3]] n1 ...
- Django框架----ORM数据库操作注意事项
1.多对多的正向查询 class Class(models.Model): name = models.CharField(max_length=32,verbose_name="班级名&q ...
- Spring5源码解析-Spring框架中的单例和原型bean
Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...
- 如何将OpenCV中的Mat类绑定为OpenGL中的纹理
https://blog.csdn.net/TTTTzTTTT/article/details/53456324 如果要调用外接的USB摄像头获取图像通常使用OpenCV来调用,如何调用摄像头请参考本 ...
- Django里自定义用户登陆及登陆后跳转到登陆前页面的实现
def logout(request): request.session.flush() return HttpResponseRedirect(request.META.get('HTTP_REFE ...
- js 解密 16进制转10进制,再取ascii码的对应值
如:\x64 对应 16进制 0x64 转10进制就是 0x64.toString(10) == 100, 查对应的ascii码表得到 ‘d' <div id=code style='displ ...