Java 调用C#或者VB生成的exe

3 篇文章 0 订阅

一. 思路

将多个参数封装到javaBean中,然后将其序列化为json字符串,
然后通过Runtime.getRuntime().exec()调用exe文件


二. 调用C#生成的exe

java

import com.fasterxml.jackson.core.io.JsonStringEncoder;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class ParamExecute1 implements CommandLineRunner {

    public void run(String... args) throws Exception {
		
		// 将参数封装到实体类中
        ParamEntity paramEntity = new ParamEntity();
        paramEntity.setName("贾飞天");
        paramEntity.setAge("28");
        paramEntity.setAddressList(Arrays.asList("地址1", "地址2"));
		
		// 通过jackson将实体类序列化为字符串
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(paramEntity);
		
		/*
			给json字符串添加转义符号:例如从 {"name": "贾飞天"} => {\"name\":\"贾飞天\"]}
			如果不加转义符号,C#端在转义的时候会报错
		*/ 
        JsonStringEncoder jsonStringEncoder = JsonStringEncoder.getInstance();
        String jsonString = new String(jsonStringEncoder.quoteAsString(jsonStr));
		
		// exe文件所在的路径
        String exePath1 = "XXX\\ConsoleApp1.exe";
        
 		// 准备参数
        List<String> paramList = new ArrayList<>();
        paramList.add(exePath1);
        paramList.add(jsonString );
        String[] paramArray = paramList.toArray(new String[0]);
        
        // 将数组传入.exec()方法中,相当于 java -version这种形式的命令行执行,中间不能有空格,否则C#端无法正确接收参数
        Process process = Runtime.getRuntime().exec(paramArray);
        
        // 执行完成后,获取inputStream流对象
        InputStream is = process.getInputStream();

        // 使用"UTF-8"编码模式,读取返回的数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder returnError = new StringBuilder();
        String line = "";

        // 只要返回对象不为空,说明exe执行的时候报错了(我们设定为报错的时候,会在C#端打印控制台)
        while ((line = reader.readLine()) != null) {
            returnError.append(line);
        }

        // 打印exe返回的报错消息
        String returnErrorStr = returnError.toString();
        System.out.println(returnErrorStr);

        // 获取exe的状态码
        int exitCode = process.waitFor();
        System.out.println(exitCode);

        // 关闭各种流
        is.close();
        reader.close();
        process.destroy();
    }
}

C#

C#侧需要去NuGet安装Newtonsoft.Json依赖
在这里插入图片描述

using Newtonsoft.Json;
using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
        	// 当未传入参数的时候,会报错
            bool result = args.Any(x => string.IsNullOrEmpty(x));
            if (result)
            {
                Console.WriteLine("Please pass in parameters");
            }

            try
            {	
            	// 获取java侧传入的json字符串
                string param = args[0];
				
				// 将json字符串转换为对象
                Person person = JsonConvert.DeserializeObject<Person>(param);
                Console.WriteLine("convert jsonStr to Object Success!!!");
				
				// 根据参数对象进行业务操作
               
            } catch(Exception e)
            {
                Console.WriteLine(e);
            }
            
        }
    }
}

效果
在这里插入图片描述


三. 调用VB生成的exe

java

// java侧和C#侧基本一致,只是需要将下面这两行json字符串转义操作删除
JsonStringEncoder jsonStringEncoder = JsonStringEncoder.getInstance();
String jsonString = new String(jsonStringEncoder.quoteAsString(jsonStr));

vb

vb侧需要去NuGet安装Newtonsoft.Json依赖
在这里插入图片描述

参数封装类

Public Class InputParam

    Private _name As String
    Private _age As Integer
    Private _addressList As List(Of String)

    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            _name = value
        End Set
    End Property

    Public Property Age As Integer
        Get
            Return _age
        End Get
        Set(value As Integer)
            _age = value
        End Set
    End Property

    Public Property AddressList As List(Of String)
        Get
            Return _addressList
        End Get
        Set(value As List(Of String))
            _addressList = value
        End Set
    End Property

End Class
Imports Newtonsoft.Json.Linq

Module Module1

    Sub Main()
        Dim Commands As String = Microsoft.VisualBasic.Command()
        Dim args As String()
		' 定义转换后的通用对象
        Dim js As JObject

        ' 获取java传入vb端的参数json字符串
        args = Commands.Split(" ")
        
        If args IsNot Nothing And args.Length > 0 Then
        
			' 定义一个InputParam,用来将参数json字符串反序列化为一个对象
        	Dim inputParam As InputParam = Nothing
        
            Try
            	' 将json字符串转换为通用对象
                js = JObject.Parse(args(0))
                
				' 将通用对象转换为我们指定的对象
                inputParam = js.ToObject(Of InputParam)
                Console.WriteLine("convert jsonStr to Object Success!!!")
				
				' 根据参数封装对象进行业务操作.....
				
            Catch ex As Exception
                Console.WriteLine(ex.ToString)
            End Try
        End If
        
    End Sub
    
End Module

效果
在这里插入图片描述

参考资料
1.https://www.cnblogs.com/excellencesy/p/11295054.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值