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, "/");
    }
    
}
AI 代码解读
相关文章
MySQL 备份 Shell 脚本:支持远程同步与阿里云 OSS 备份
一款自动化 MySQL 备份 Shell 脚本,支持本地存储、远程服务器同步(SSH+rsync)、阿里云 OSS 备份,并自动清理过期备份。适用于数据库管理员和开发者,帮助确保数据安全。
|
2天前
|
在Linux、CentOS7中设置shell脚本开机自启动服务
以上就是在CentOS 7中设置shell脚本开机自启动服务的全部步骤。希望这个指南能帮助你更好地管理你的Linux系统。
46 25
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
JVM实战—1.Java代码的运行原理
本文介绍了Java代码的运行机制、JVM类加载机制、JVM内存区域及其作用、垃圾回收机制,并汇总了一些常见问题。
JVM实战—1.Java代码的运行原理
|
2月前
|
【linux】Shell脚本中basename和dirname的详细用法教程
本文详细介绍了Linux Shell脚本中 `basename`和 `dirname`命令的用法,包括去除路径信息、去除后缀、批量处理文件名和路径等。同时,通过文件备份和日志文件分离的实践应用,展示了这两个命令在实际脚本中的应用场景。希望本文能帮助您更好地理解和应用 `basename`和 `dirname`命令,提高Shell脚本编写的效率和灵活性。
147 32
定期备份数据库:基于 Shell 脚本的自动化方案
本篇文章分享一个简单的 Shell 脚本,用于定期备份 MySQL 数据库,并自动将备份传输到远程服务器,帮助防止数据丢失。
多种脚本批量下载 Docker 镜像:Shell、PowerShell、Node.js 和 C#
本项目提供多种脚本(Shell、PowerShell、Node.js 和 C#)用于批量下载 Docker 镜像。配置文件 `docker-images.txt` 列出需要下载的镜像及其标签。各脚本首先检查 Docker 是否安装,接着读取配置文件并逐行处理,跳过空行和注释行,提取镜像名称和标签,调用 `docker pull` 命令下载镜像,并输出下载结果。使用时需创建配置文件并运行相应脚本。C# 版本需安装 .NET 8 runtime。
169 2
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。

热门文章

最新文章

下一篇
oss创建bucket
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等