Home Articles

如何从qt creator向外部jar文件提供运行时输入

Asked
Viewed 1779 times
2

我搜索了这个主题但是得到了解决方案 .

我正在开发qt小部件应用程序来运行外部jar文件并在qt gui touch diaplay上显示jar输出 . 以这种方式,我的外部jar文件,在用户给出运行时输入时执行,然后处理并打印输出 . (读取和写入)这里,我使用QProcess执行jar文件 . 进程(jar执行)开始运行,等待用户输入 . 我无法通过qt控制台和终端窗口向我的外部jar文件提供运行时输入 . 请建议如何通过qt从外部jar文件写回输入和读取输出 .

这是我们的jar(sample.jar)包含的java应用程序文件(.java) . 将此.java文件导出为可执行的sample.jar文件 .

import java.util.Scanner;

public class RuntimeInput {

public static void main(String args[]){
    System.out.println("Reading jar file");

    System.out.println("Enter Consumer No: ");

    Scanner inputReader = new Scanner(System.in);

    String name = inputReader.nextLine();
    System.out.println("Hi " + name);

}
}


 **Expected Qt output:** 

在cmd窗口中运行可执行jar就像这样,

D:> java -jar sample.jar

读取jar文件输入Consumer No:124569896 Hi 124569896

```java
mainwindow.cpp 

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QTextStream>
#include <QByteArray>
#include <QProcess>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{

        cmd = new QProcess(this);

        connect( cmd, SIGNAL(readyReadStandardError()), this, SLOT(handleReadStandardError()) );

        connect( cmd, SIGNAL(readyReadStandardOutput()), this, SLOT(handleReadStandardOutput()) );

        QStringList arguments;
        arguments << "-jar" << "D:\\sample.jar";

        cmd->start("java",  arguments, QIODevice::ReadWrite);

        //cmd->execute("java -jar D:\\sample.jar");

        if ( cmd->state() == QProcess::NotRunning ) {
           qDebug() << "The process is not running.It exits";
        }
        else if ( cmd->state() == QProcess::Starting ) {
            qDebug() << "The process is started, but the program has not yet been invoked.";
        }else if ( cmd->state() == QProcess::Running ) {
            qDebug() << "The process is running and is ready for reading and writing.";
        }

        if (!cmd->waitForStarted())  {
           qDebug() << "Not yet started";

        }

}

void MainWindow::handleReadStandardError()
{
    QByteArray data = cmd->readAllStandardError();
    qDebug() << data;
    ui->textEdit->append(QString(data));
}

void MainWindow::handleReadStandardOutput()
{
   QByteArray data = cmd->readAllStandardOutput();
   qDebug() << "Data:\n" << data << endl;
   ui->textEdit->append(QString(data));

}

QT Console output:

启动D:\ ANNIE \ QT Workspace \ build-Samplewrite-Desktop_Qt_5_7_1_MinGW_32bit-Debug \ debug \ Samplewrite.exe ...进程正在运行,可以进行读写 . 数据:

“读取jar文件\ r \ n输入消费者编号:\ r \ n”

1 Answer

  • 0

    QProcess继承自OIODevice,因此您可以使用write()函数将数据写入其标准输入:

    cmd->write("124569896\n");
    

Related