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, "/");
    }
    
}
相关文章
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
1058 7
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
518 1
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
703 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1080 5
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
492 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
956 0
|
Java 关系型数据库 MySQL
Java汽车租赁系统源码(含数据库脚本)
Java汽车租赁系统源码(含数据库脚本)
873 4
|
文字识别 监控 Java
顺丰同城抢单辅助脚本,顺丰骑士抢单辅助免封号,自动抢单神器【java版开源】
这是一套OCR实时检测订单列表并自动右滑的完整代码方案,适用于学习研究。代码包含四个主要模块:OCR处理(文字识别)、价格分析
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
703 0