【问题标题】:Get the Output of a Java String From VBA从 VBA 获取 Java 字符串的输出
【发布时间】:2020-11-25 13:20:13
【问题描述】:

我需要将 java 函数的输出字符串放入我的 VBA 项目中。作为一个快速示例,我试图获取安装的 java 版本的输出,但在实际应用程序中它将是其他私有函数。

第一次尝试:

' Needs a reference to Windows Script Host Object Model
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub get_java_output()
    Dim cmd_windows    As New WshShell
    Dim execution_cmd  As WshExec
    Dim command_str    As String
    command_str = "java -version"
    Set execution_cmd = cmd_windows.exec("cmd.exe /c " & command_str)
    Do While execution_cmd.Status = WshRunning
        Sleep 20
    Loop
    final_string = execution_cmd.StdOut.ReadAll
    Debug.Print final_string
End Sub

第二次尝试:

Sub get_java_output_2()
    Dim windows_shell As Object
    
    Set windows_shell = CreateObject("WScript.Shell")
    command_str = "java -version"
    shell_output = windows_shell.Run("cmd /c " & command_str & " > c:\temp\output.txt", 0, False)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set File = fso.OpenTextFile("c:\temp\output.txt", 1)
    final_string = File.ReadAll
    File.Close
    Debug.Print final_string
End Sub

它们都不适合我。

我想避免在我的第二次尝试示例中使用临时文件。在最终的使用中,我会调用这个函数几十万次,我不希望创建那么多文件或编辑那个文件那么多次......

【问题讨论】:

  • 这实际上与 Java 本身无关。您正在尝试捕获通过 shell 命令调用的进程的输出。也许这里的答案之一可能会对您有所帮助:stackoverflow.com/questions/2784367/…

标签: java vba


【解决方案1】:

我已经找到了两种尝试的解决方案,基本上它是同一个问题:命令 shell 上显示的 java 函数的输出被视为错误,因此它不是输出。 The doubt was solved here

在将 java 输出发送到文件的情况下,使用 2> 而不是像 here 所说的那样仅使用 > 来解决它。无论如何,根据您的需要,有很多不同的变体,如this other link 中所述。此方法的一个小问题是输出文件的创建需要时间,因此Run命令的最终变量必须设置为True

代码如下:

Sub get_java_output_2()
    Dim windows_shell As Object
    
    Set windows_shell = CreateObject("WScript.Shell")
    command_str = "java -version"
    shell_output = windows_shell.Run("cmd /c " & command_str & " 2> c:\temp\output.txt", 0, True)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set File = fso.OpenTextFile("c:\temp\output.txt", 1)
    final_string = File.ReadAll
    File.Close
    Debug.Print final_string
End Sub

在直接将java输出到变量的情况下,使用StdErr而不是StdOut来解决。 我得到了照明读数this linkWshExec 对象具有三个主要元素:StdErrStdInStdOut。如果 java 输出字符串被视为错误,则应该在 StdErr 内。

代码如下:

' Needs a reference to Windows Script Host Object Model
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sub get_java_output()
    Dim cmd_windows    As New WshShell
    Dim execution_cmd  As WshExec
    Dim command_str    As String
    command_str = "java -version"
    Set execution_cmd = cmd_windows.exec(command_str)
    Do While execution_cmd.Status = WshRunning
        Sleep 20
    Loop
    final_string = execution_cmd.StdErr.ReadAll
    Debug.Print final_string
End Sub

【讨论】:

    猜你喜欢
    • 2019-06-19
    • 2020-12-19
    • 2011-11-15
    • 2017-10-16
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2017-02-15
    • 2016-07-27
    相关资源
    最近更新 更多