-
Notifications
You must be signed in to change notification settings - Fork 1
/
2010-05-09-java-runtime-exec.html
141 lines (129 loc) · 6.53 KB
/
2010-05-09-java-runtime-exec.html
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Qnikst blog - java//Runtime exec</title>
<!-- Bootstrap -->
<link href="../css/bootstrap.min.css" rel="stylesheet" media="screen">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../js/bootstrap.min.js"></script>
</head>
<body>
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<a class="brand" href="../">Qnikst blog</a>
<ul class="nav ">
<li class="active"><a href="../">Home</a></li>
<li><a href="../posts.html">Blog</a></li>
<li><a href="../projects.html">Projects</a></li>
<li><a href="../contact.html">Contacts</a></li>
</ul>
</div>
</div>
<div class="container">
<div class="page-header">
<h1>java//Runtime exec <br /><small><strong>May 9, 2010</strong></small></h1>
</div>
<p>Поскольку в одной совершенно не требующей этого задаче мне пришлось столкнуться с тем, что нужно было осуществить взаимодействие со внешней программой. Я решил в этом немного разобраться и натолкнулся на большое количество тем с вопросами, так, что тут небольшая подборка всего этого безобразия.</p>
<h2 id="запуск-внешней-программы">Запуск внешней программы</h2>
<p>запуск внешней программы в Java осуществляется вызовом метода <code>Runtime exec(String[] command,String[] env);</code>. Передача параметрF массивом нужна, что того чтобы с ними было меньше проблем, например с пробелами. Ожидание завершения программы производится вызовом метода <code>int waitFor(0)</code> и мы получаем возвращаемое процессом значение. Так же есть методы:</p>
<ul>
<li><code>destoy</code> - завершение процесса, и</li>
<li><code>exitValue</code> – возвращающий значение выхода или исключение, если процесс не завершён.</li>
</ul>
<p>Итого код примера:</p>
<pre><code>String cmd = {"cat","--help"};
Process pCat = System.getRuntime().exec(cmd);
pCat.waitFor();</code></pre>
<h2 id="перенаправление-потока-внешней-программы">Перенаправление потока внешней программы</h2>
<p>Часто перед нами стоит задача получение доступа к потокам ввода-вывода программы. Это делается следующими методами:</p>
<table>
<tr><td>
Метод
</td><td>
Возвращаемый тип
</td><td>
что такое
</td></tr>
<tr><td>
getOutputStream
</td><td>
OutputStream
</td><td>
поток ввода программы (stdin)
</td></tr>
<tr><td>
getInputStream
</td><td>
InputStream
</td><td>
поток вывода программы(stdout)
</td></tr>
<tr><td>
getErrorStream
</td><td>
InputStream
</td><td>
поток ошибок программы(stderr)
</td></tr>
</table>
<p>NOTE Да, названия методов немного не логичны.</p>
<p>Пример получения потоков:</p>
<pre><code>stdin = pCat.getOutputStream();
stdout = pCat.getInputStream();
stderr = pCat.getErrorStream();
String line =”hello world” + “\n”;
stdin.write(line.getBytes()); //отправляем данные программе
stdin.flush();
stdin.close();
BufferedReader outReader = new BufferedReader(new InputStreamReader(stdout));
while ((line = outReader.readLine ()) != null) { //считываем поток выхода
System.out.println (line);
}
outReader.close();
BufferedReader errReader = new BufferedReader(new InputStreamReader(stderr));
while ((line = errReader.readLine ()) != null) { //считываем поток ошибок
System.out.println (“[Stderr] ” + line);
}
errReader.close();</code></pre>
<p>Замечу, что в данной программе есть налог клавиши ctrl+D это <code>stdin.close();</code> =)</p>
<hr />
<div class="pull-right">
<em>Alexander Vershilov</em>
<a href="http://creativecommons.org/licenses/by-nc-sa/3.0"><img src="http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png" /></a>
</div>
<br class="clearfix" />
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'qnikst'; // required: replace example with your forum shortname
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
<footer>
Site generated using <a href="http://jaspervdj.be/hakyll">Hakyll</a> using <a href="http://johnmacfarlane.net/pandoc/">pandoc</a>
</footer>
</div>
<script type="text/javascript">
// <noscript> я очень хочу вас посчитать, напишите комментарий хотя бы, пожааалуйста </noscript>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-38941774-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>