Hello,
j'ai une petite question et une réponse, mais je ne suis pas certain que ma solution est optimale.
Je lance un process qui produit des outputs + ou - important dans les stderr et stdout. J'ai bien trouvé sur la FAQ des réponses pour récupérer les Streams, mais on ne fait que lire tout un Stream et puis ensuite tout le 2e. Si le buffer du 2e est à un moment plein, le process est bloqué et le programme ne se stoppe pas. Ma solution, 2 Threads. Je ne sais pas si c'est la bonne méthode. Si quelqu'un pouvez-vous m'éclairer: me dire si c'est bien, pas bien ou comment je peux améliorer les choses ...
Dans ce cas, c'est un dir tout simple, mais normalement, je dois exécuter un programme sur lequel je n'ai pas de contrôle (acheté).
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69 package monpackage; import java.io.IOException; import java.io.InputStream; public class Main { class MyThread extends Thread { private StringBuffer buf; private InputStream in; public MyThread(StringBuffer buf, InputStream in) { this.buf = buf; this.in = in; } public void run() { synchronized (buf) { int b = 0; try { while ((b = in.read()) != -1) { buf.append((char) b); } } catch (IOException e) { e.printStackTrace(); } } } }; private volatile boolean running; public static void main(String[] args) throws IOException, InterruptedException { new Main(); } public Main() throws IOException, InterruptedException { final StringBuffer outBuf = new StringBuffer(); final StringBuffer errBuf = new StringBuffer(); Process process = null; try { process = Runtime.getRuntime().exec("cmd /c dir /s"); } catch (IOException e) { e.printStackTrace(); } final InputStream out = process.getInputStream(); final InputStream err = process.getErrorStream(); MyThread readOutThread = new MyThread(outBuf, out); MyThread readErrThread = new MyThread(errBuf, err); process.getOutputStream().close(); readErrThread.start(); readOutThread.start(); process.waitFor(); synchronized (outBuf) { out.close(); } synchronized (errBuf) { err.close(); } System.out.print(outBuf.toString()); System.err.print(errBuf.toString()); System.out.println("Process RC: " + process.exitValue()); } }
Merci
Partager