Java中操作Linux命令实现文件传输(详细)

Java中操作Linux命令实现文件传输(详细)

一直想记录一下我这个文章的,但一直没想起来。之前做了一个java操作linux命令操作文件的东西,其实我当时也是百度,实际的代码其实就拿几行,希望能帮到大家!

java代码

/**
 * 操作linux工具类
 */
public class ExcuteLinux {
    
    
    private static final Logger logger = LoggerFactory.getLogger(ExcuteLinux.class);

    /**
     * 通过cp命令拷贝
     *
     * @param command
     * @return
     * @throws IOException
     */
    public static String run(String command) throws IOException {
    
    
        Scanner input = null;
        String result = "";
        Process process = null;
        try {
    
    
            process = Runtime.getRuntime().exec(command);
            try {
    
    
                //等待命令执行完成
                process.waitFor(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            InputStream is = process.getInputStream();
            input = new Scanner(is);
            while (input.hasNextLine()) {
    
    
                result += input.nextLine() + "\n";
            }
            result = command + "\n" + result; //加上命令本身,打印出来
            logger.info("命令:" + result);
        } finally {
    
    
            if (input != null) {
    
    
                input.close();
            }
            if (process != null) {
    
    
                process.destroy();
            }
        }
        return result;
    }
}

这个是封了一个工具类,其中运用到的就是方法中Process类,大家可以下去自己看看这个类。通过这个类,项目上传服务器后就可以直接操作文件!还有一种方法是在本地项目启动时操作linux命令,这个等我下篇文章喽!

废话太多了,赶紧言归正传

java 代码

 private String cpFile(List<String> param) throws IOException {
    
    
        List<String> rename = renameFiles(param);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        // new Date()为获取当前系统时间
        String path = df.format(new Date());
        File file=new File(customConfig.getRhTargetFileFolder() + path);
        //ExcuteLinux.run("mkdir " + customConfig.getRhTargetFileFolder() + path); //创建文件
        createDirectoryQuietly(file);
        for (int i = 0; i < param.size(); i++) {
    
    
            for (int j = 0; j < rename.size(); j++) {
    
    
                ExcuteLinux.run("cp -r " + param.get(i) + " " + customConfig.getRhTargetFileFolder() + path + "/" + rename.get(i));//在服务器上可执行的shell命令
                ++j;
                break;
            }
        }
        return path;
    }

上述代码中呢除了红框内的代码,红框外的就不要管,那是我自己的逻辑

在这里插入图片描述

通过工具类的里的方法,参数就是要使用的命令,我这边使用的 cp 拷贝的命令,就可以实现文件之间的相互拷贝我其余的逻辑也就是获取文件名,什么的,大家根据自己需求来,但使用命令操作的就是,一个工具类,一个调用!

在这里插入图片描述

欢迎大家收看王不正讲技术,每年不知何时更新,大家随机等待哦!哈哈哈!每天记录一点,成长你我他哦!

猜你喜欢

转载自blog.csdn.net/m0_46379371/article/details/108528202
今日推荐