Java - passaggio di input in un'applicazione C / C ++ esterna
-
07-07-2019 - |
Domanda
Sto cercando di inserire un valore nell'applicazione esterna usando Java.
L'applicazione Java è simile alla seguente:
Runtime runtime = Runtime.getRuntime();
// ... str build ...
proc = runtime.exec(str);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
bw.write(value);
bw.flush();
bw.close();
if (proc.waitFor() != 0)
// error msg
// the end
L'applicazione si blocca nel metodo waitFor.
L'applicazione esterna è simile a questa:
welcome banner
please enter 8 character input:
Il banner di benvenuto viene stampato utilizzando printf e l'input viene acquisito con SetConsoleMode / ReadConsoleInput. ReadConsoleInput legge un carattere e sono mascherati con il carattere *.
Aiuto
Soluzione 2
Hai la risposta! Il trucco è usare l'API WriteConsoleInput () perché il programma prevede l'evento da tastiera, non il testo ... Ecco perché waitFor () ha aspettato per sempre! :)
Altri suggerimenti
puoi usare:
proc.getOutputStream().write("some date".getBytes())
tieni presente che DEVI leggere tutto ciò che l'app invia a stdout e stderr, altrimenti potrebbe bloccarsi a scrivere lì. Uso una classe generica per leggerlo in un thread diverso. l'utilizzo è come:
InputStreamSucker inSucker = new InputStreamSucker(proc.getInputStream());
InputStreamSucker errSucker = new InputStreamSucker(proc.getErrorStream());
proc.waitFor();
int exit = process.exitValue();
inSucker.join();
errSucker.join();
Il codice InputStreamSucker è qui:
public class InputStreamSucker extends Thread
{
static Logger logger = Logger.getLogger(InputStreamSucker.class);
private final BufferedInputStream m_in;
private final ByteArrayOutputStream m_out;
private final File m_outFile;
public InputStreamSucker(InputStream in) throws FileNotFoundException
{
this(in, null);
}
public InputStreamSucker(InputStream in, File outFile) throws FileNotFoundException
{
m_in = new BufferedInputStream(in, 4096);
m_outFile = outFile;
m_out = new ByteArrayOutputStream();
start();
}
@Override
public void run()
{
try
{
int c;
while ((c = m_in.read()) != -1)
{
m_out.write(c);
}
}
catch (IOException e)
{
logger.error("Error pumping stream", e);
}
finally
{
if (m_in != null)
{
try
{
m_in.close();
}
catch (IOException e)
{
}
}
try
{
m_out.close();
}
catch (IOException e)
{
logger.error("Error closing out stream", e);
}
if (m_outFile != null)
{
byte data[] = m_out.toByteArray();
if (data.length > 0)
{
FileOutputStream fo = null;
try
{
fo = new FileOutputStream(m_outFile);
fo.write(data);
}
catch (IOException e)
{
logger.error("Error writing " + m_outFile);
}
finally
{
try
{
if (fo != null) fo.close();
}
catch (IOException e)
{
logger.error("Error closing " + m_outFile);
}
}
}
}
}
}
public String getOutput()
{
return new String(m_out.toByteArray());
}
}