java运行shell脚本操作文件

简介: java运行shell脚本操作文件
import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**运行shell脚本
 * 
 *
 */
public class RunShellUtil {
    
    private static final Logger logger=LoggerFactory.getLogger(RunShellUtil.class);
    
    /**运行链接文件
     * @param sourceFile
     * @param distFile
     * @return
     * @throws Exception
     */
    public static int runLinkFile(String sourceFilePath,String distFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将 {} 硬连接 到{}", sourceFilePath,distFilePath));
        String[] command=getLinkFileCommand(sourceFilePath,distFilePath);
        int code = executeShellCommand(command);
        return code;
    }
    
    /**链接文件夹
     * @param sourceFilePath
     * @param disFilePath
     * @return
     * @throws Exception
     */
    public static int runLinkDirectory(String sourceFilePath,String disFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将文件夹 {} 硬链接到 {}", sourceFilePath,disFilePath));
        File sourceDirectory=new File(sourceFilePath);
        File disDirectory=new File(disFilePath);
        disDirectory.mkdirs();
        File[] fileList=sourceDirectory.listFiles();
        if(null == fileList || fileList.length == 0){
            return 0;
        }
        
        for(File file:fileList){
            String currentName=file.getName();
            String absolutePath=file.getAbsolutePath();
            String disAbsolutePath=joinFilePath(disFilePath,currentName);
            if(file.isDirectory()){
                runLinkDirectory(absolutePath,disAbsolutePath);
            }else{
                runLinkFile(absolutePath,disAbsolutePath);
            }
        }
        
        return 0;
    }
    
    /**获取文件链接命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    private static String[] getLinkFileCommand(String sourceFilePath,String distFilePath) throws Exception{
        EPlatform platform=OSinfoUtil.getOsName();
        String command[]=null;
        if(platform.equals(EPlatform.Linux)){
            
            sourceFilePath=FilePathUtil.processUniqueC(sourceFilePath);
            distFilePath=FilePathUtil.processUniqueC(distFilePath);
//            
//            command="ln "+sourceFilePath+" "+distFilePath;
//            command=StringUtil.format("/bin/sh -c ln {} {}",sourceFilePath,distFilePath);
            
            command=new String[]{"/bin/sh","-c",StringUtil.format("ln {} {}", sourceFilePath,distFilePath)};
        }else {
            throw new FileOperateException("操作系统 {} 不支持文件链接",platform.toString());
        }
        return command;
    }
    
    /**移动文件
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    public static int runMoveFile(String sourceFilePath,String distFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将 {} 移动到 {}", sourceFilePath,distFilePath));
        String command=getMoveFileCommand(sourceFilePath,distFilePath);
        int code=executeShellCommand(command);
        return code;
    }
    
    /**运行移动文件夹命令
     * @param sourceFilePath
     * @param disFilePath
     * @return
     * @throws Exception
     */
    public static int runMoveDirectory(String sourceFilePath,String disFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将文件夹 {} 移动到 {}", sourceFilePath,disFilePath));
        String command=getMoveDirectoryCommand(sourceFilePath,disFilePath);
        int code=executeShellCommand(command);
        return code;
    }
    
    /**获取移动文件命令
     * @param sourceFilePath
     * @param fistFilePath
     * @return
     */
    private static String getMoveFileCommand(String sourceFilePath,String distFilePath) throws Exception{
        EPlatform platform=OSinfoUtil.getOsName();
        String command=null;
        if(platform.equals(EPlatform.Windows)){
            //windows
            command="cmd /c move "+sourceFilePath+" "+distFilePath;
        }else if(platform.equals(EPlatform.Linux)){
            //linux
            command="mv "+sourceFilePath+" "+distFilePath;
        }else{
            throw new FileOperateException(StringUtil.format("该系统 {} 不支持文件移动命令", platform));
        }
        return command;
    }
    
    /**获取移动文件夹命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    private static String getMoveDirectoryCommand(String sourceFilePath,String distFilePath) throws Exception{
        EPlatform platform=OSinfoUtil.getOsName();
        String command=null;
        if(platform.equals(EPlatform.Windows)){
            //windows
            command="cmd /c move "+sourceFilePath+" "+distFilePath;
        }else if(platform.equals(EPlatform.Linux)){
            //linux
            command="mv -fr "+sourceFilePath+" "+distFilePath;
        }else{
            throw new FileOperateException(StringUtil.format("该系统 {} 不支持文件夹移动命令", platform));
        }
        return command;
    }
    
    /**运行复制文件命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    public static int runCopyFile(String sourceFilePath,String distFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将 {} 复制到 {}", sourceFilePath,distFilePath));
        String command=getCopyFileCommand(sourceFilePath,distFilePath);
        int code=executeShellCommand(command);
        return code;
    }
    
    /**运行复制文件夹命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Excetion
     */
    public static int runCopyDirectory(String sourceFilePath,String distFilePath) throws Exception{
        logger.info(StringUtil.format("开始执行命令将文件夹 {} 复制到 {}", sourceFilePath,distFilePath));
        String command=getCopyDirectoryCommand(sourceFilePath,distFilePath);
        int code=executeShellCommand(command);
        return code;
    }
    
    /**获取文件复制命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    private static String getCopyFileCommand(String sourceFilePath,String distFilePath) throws Exception{
        EPlatform platform=OSinfoUtil.getOsName();
        String command=null;
        if(platform.equals(EPlatform.Windows)){
            command="cmd /c Copy "+sourceFilePath+" "+distFilePath;
        }else if(platform.equals(EPlatform.Linux)){
            command="cp "+sourceFilePath+" "+distFilePath;
        }else{
            throw new FileOperateException("操作系统 {} 不支持文件复制",platform.toString());
        }
        return command;
    }
    
    /**获取复制文件夹命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    private static String getCopyDirectoryCommand(String sourceFilePath,String distFilePath) throws Exception{
        EPlatform platform=OSinfoUtil.getOsName();
        String command=null;
        if(platform.equals(EPlatform.Windows)){
            //windows
            command="cmd /c Copy "+sourceFilePath+" "+distFilePath;
        }else if(platform.equals(EPlatform.Linux)){
            //linux
            command="cp -r "+sourceFilePath+" "+distFilePath;
        }else{
            throw new FileOperateException("操作系统 {} 不支持文件夹复制",platform.toString());
        }
        return command;
    }
    
    /**执行shell命令
     * @param sourceFilePath
     * @param distFilePath
     * @return
     * @throws Exception
     */
    public static int executeShellCommand(String... command) throws Exception{
        Process process  = Runtime.getRuntime().exec(command);
        InputStreamReader ir = new InputStreamReader(process
                .getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        StringBuffer b=new StringBuffer();
        while ((line = input.readLine()) != null) {  
              b.append(b);
        } 
        
        int code = process.waitFor();
        logger.info(StringUtil.format("执行命令 {} 返回code {} 返回内容 {}", NormalUtil.join(command," "),code,b.toString()));
        if(code != 0){
            throw new Exception(StringUtil.format("执行命令 {} 出错,{}", command.toString(),b.toString()));
        }
        return code;
    }

    public static  List<String> runShell(String shStr) throws Exception {
        List<String> strList = new ArrayList<String>();

        Process process;
        process = Runtime.getRuntime().exec(new String[] {"/bin/sh","-c",shStr},null,null);
        InputStreamReader ir = new InputStreamReader(process
                .getInputStream());
        LineNumberReader input = new LineNumberReader(ir);
        String line;
        process.waitFor();
        while ((line = input.readLine()) != null) {
            strList.add(line);
        }

        return strList;
    }
    
    /**文件路径连接
     * @param paths
     * @return
     */
    public static String joinFilePath(String...paths){
        if(null == paths || paths.length == 0){
            return null;
        }
        return NormalUtil.join(paths, "/");
    }
    
}
相关文章
|
13天前
|
存储 安全 Unix
七、Linux Shell 与脚本基础
别再一遍遍地敲重复的命令了,把它们写进Shell脚本,就能一键搞定。脚本本质上就是个存着一堆命令的文本文件,但要让它“活”起来,有几个关键点:文件开头最好用#!/usr/bin/env bash来指定解释器,并用chmod +x给它执行权限。执行时也有讲究:./script.sh是在一个新“房间”(子Shell)里跑,不影响你;而source script.sh是在当前“房间”里跑,适合用来加载环境变量和配置文件。
215 9
|
13天前
|
存储 Shell Linux
八、Linux Shell 脚本:变量与字符串
Shell脚本里的变量就像一个个贴着标签的“箱子”。装东西(赋值)时,=两边千万不能有空格。用单引号''装进去的东西会原封不动,用双引号""则会让里面的$变量先“变身”再装箱。默认箱子只能在当前“房间”(Shell进程)用,想让隔壁房间(子进程)也能看到,就得给箱子盖个export的“出口”戳。此外,Shell还自带了$?(上条命令的成绩单)和$1(别人递进来的第一个包裹)等许多特殊箱子,非常有用。
79 2
|
6月前
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
433 7
|
1月前
|
数据采集 监控 Shell
无需Python:Shell脚本如何成为你的自动化爬虫引擎?
Shell脚本利用curl/wget发起请求,结合文本处理工具构建轻量级爬虫,支持并行加速、定时任务、增量抓取及分布式部署。通过随机UA、异常重试等优化提升稳定性,适用于日志监控、价格追踪等场景。相比Python,具备启动快、资源占用低的优势,适合嵌入式或老旧服务器环境,复杂任务可结合Python实现混合编程。
|
4月前
|
Shell
Shell脚本循环控制:shift、continue、break、exit指令
使用这些命令可以让你的Shell脚本像有生命一样动起来。正确使用它们,你的脚本就能像一场精心编排的舞蹈剧目,既有旋律的起伏,也有节奏的跳跃,最终以一场惊艳的表演结束。每一个动作、每一个转折点,都准确、优雅地完成所需要表达的逻辑。如此,你的脚本不只是冰冷的代码,它透过终端的界面,跳着有节奏的舞蹈,走进观众——使用者的心中。
207 60
|
3月前
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
209 14
|
3月前
|
Web App开发 缓存 安全
Linux一键清理系统垃圾:释放30GB空间的Shell脚本实战​
这篇博客介绍了一个实用的Linux系统盘清理脚本,主要功能包括: 安全权限检查和旧内核清理,保留当前使用内核 7天以上日志文件清理和系统日志压缩 浏览器缓存(Chrome/Firefox)、APT缓存、临时文件清理 智能清理Snap旧版本和Docker无用数据 提供磁盘空间使用前后对比和大文件查找功能 脚本采用交互式设计确保安全性,适合定期维护开发环境、服务器和个人电脑。文章详细解析了脚本的关键功能代码,并给出了使用建议。完整脚本已开源,用户可根据需求自定义调整清理策略。
238 1
|
3月前
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
|
5月前
|
存储 Unix Shell
确定Shell脚本在操作系统中的具体位置方法。
这对于掌握Linux的文件系统组织结构和路径方面的理解很有帮助,是我们日常工作和学习中都可能使用到的知识。以上讲解详细清晰,应用简便,是每一个想要精通操作系统的计算机爱好者必备的实用技能。
112 17
|
3月前
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
195 0

热门文章

最新文章