浅析C++调用Java的Jar包(带参数)问题

这篇文章主要介绍了C++调用Java的Jar包(带参数)问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

JarAppCall.h


#include <atlstr.h>
class CJarAppCall
{
    public:
        CJarAppCall(void);
        ~CJarAppCall(void);
        /*
        @brief 运行Jar包调用,等待运行完毕返回
        @param[in] strJarDir jar包文件夹
        @param[in] strJarName jar包名称<br>          @param[in] strParam 传入的参数
        @return 运行是否成功
        */
        bool Run(const CString& strJarDir, const CString& strJarName, const CString& strParam);
 
    private:
        bool CallApp(const CString& strJarName, const CString& strParam);
};

JarAppCall.cpp


#include "JarAppCall.h"
CJarAppCall::CJarAppCall(void){
}
CJarAppCall::~CJarAppCall(void){
}
bool CJarAppCall::Run(const CString& strJarDir, const CString& strJarName, const CString& strParam){
    //缓存当前文件夹
    WCHAR sOldDir[MAX_PATH] = { 0 };
    GetCurrentDirectory(MAX_PATH, sOldDir);
 
    //设置当前文件夹为jar包文件夹
    SetCurrentDirectory(strJarDir);
    bool bCalRest = CallApp(strJarName, strParam);
    //还原当前文件夹
    SetCurrentDirectory(sOldDir);
    return bCalRest;
}
bool CJarAppCall::CallApp(const CString& strJarName, const CString& strParam){
    WCHAR sSysDir[MAX_PATH] = { 0 };
    GetSystemDirectory(sSysDir, MAX_PATH);
    CString strFullPath = sSysDir;
    strFullPath += _T("\\cmd.exe");
    CString strCmdLine = _T(" /C ");
    strCmdLine += _T("java -jar ");
    strCmdLine += strJarName;
    strCmdLine += _T(" ");
    strCmdLine += strParam;
 
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi;
    BOOL bRunProgram = CreateProcess(strFullPath.GetBuffer(),
        strCmdLine.GetBuffer(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
    strFullPath.ReleaseBuffer();
    strCmdLine.ReleaseBuffer();
    if (!bRunProgram){
        return false;
    }
 
    // 等待程序结束
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);
    return true;
}

test.cpp


#include "stdio.h"
#include "JarAppCall.h"
#include<stdlib.h>
#include <cstring>
#include <string>
#include <iostream>
 
int charContainsToChar(char* source, char* target);
char* getNameReferences(char* src);
 
int main(){
    /*CString strJarDir = _T("C:\\Users\\12449\\Desktop");
    CString strJarName = _T("test.jar");
 
    CJarAppCall jarCall;
    if (!jarCall.Run(strJarDir, strJarName)){
        //启动失败
        printf("启动失败");
        return 0;
    }
    printf("启动成功");*/
     
 
    //char src[] = "测.试.xlsx";
    //char test[] = "test";
    //char dataset_name[] = "PLM_021-000320.txt";
    //char* result = getNameReferences(test);
    //char* null = "NULL";
    //if (strcmp(result, null) != 0){
    //  printf("name=%s\n", 1);
    /

本文标题为:浅析C++调用Java的Jar包(带参数)问题

基础教程推荐