springboot 调用外部工具如ffmpeg工具加载类

使用场景: 有时候springboot开发的jar服务,需要调用外部的一个命令行工具文件,如ffmpeg。
我们可以将ffmpeg 放入src/main/resources/tool目录。然后java -jar 启动服务时,将ffmpeg写入到外部的一个目录,为此我特意写了一个工具类,可以在运行jar时只生成一次,或者ffmpeg版本变了覆盖刷新。

@Slf4j
@Configuration
public class LibFileInit {



    // 加载 resources目录下的工具文件相对路径 如:/tool/ffmpeg
    @Value("${system.loadLibDir}")
    private String loadLibDir;

    // 将加载的文件放入的目录 如 /sbin/
    @Value("${system.outLibDir}")
    private String outLibDir;

    // 是否每次运行服务都覆盖老版本的外部工具,默认 false
    @Value("${system.loadLibFlag}")
    private Boolean loadLibFlag;

    @Bean
    public LibFileInit FfdynsourceInit() throws IOException {

        copyFile(new String[]{loadLibDir},outLibDir,loadLibFlag);
        log.info("=====================this lib file init ok!");


        return new LibFileInit();
    }

    // 拷贝文件 flag
    public void copyFile(String[] fPaths,String outPath,Boolean flag) throws IOException{
        Boolean status  = false;
        // List<String> fPaths = new ArrayList<>();

        for (String path:fPaths){

            ResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource("classpath:"+path);
            if (resource.exists()){
                InputStream is = resource.getInputStream();

                File pathF = new File(outPath);
                if (!pathF.exists()){
                    pathF.mkdirs();
                }
                File f = new File(outPath,path.substring(path.lastIndexOf("/"),path.length()));
                log.info("create file path 文件路径:{}",f.getAbsolutePath());
                if (flag && f.exists()){
                    f.delete();
                }

                if (!f.exists()){
                    f.createNewFile();
                    f.setReadable(true);
                    f.setWritable(true);
                    f.setExecutable(true);
                    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f, false));
                    int lentgh = 0;
                    while ((lentgh = is.read()) != -1) {
                        os.write(lentgh);
                    }

                    is.close();
                    os.close();
                }
            }

        }

    }
}

更多,请关注:
springboot 技术实践总结

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容