Runtime.getRuntime().exec(”convert -resize 32x32 - -”);
詳しいは以上のようにconvertコマンドの入力ファイルを標準入力ストリームにしたいですが、どうすれば良いでしょうか?
以下このようにソースを作成したが、ダメです。理由を教えてください。
psが初期化されていないというExceptionが出ます。
Process ps;
//プロセスの標準入力生成
FileInputStream fis = (FileInputStream)is;
BufferedOutputStream std_in = new BufferedOutputStream(ps.getOutputStream());
byte[] buf = new byte[1000];
int m;
while ((m = fis.read(buf)) > 0)
std_in.write(buf, 0, m);
fis.close();
//プロセスの初期化
Runtime rt = Runtime.getRuntime();
ps = rt.exec(”convert -resize 32x32 - -”);
ケアレスミスかな?
ソースがこの通りの順序なら、プロセスの初期化をする前に標準入力生成が行われていますね。順番が逆ではないでしょうか。
プロセスの初期化のコードを、標準入力の生成の前に持ってくるべきだと思います。
WinXPで実行しています。
展開後、
java ExecCommand
Java ExecCommand2
で実行できるはずです。
ExecCommand.java hostnameコマンドの実行結果を標準入力から受け取る
ExecCommand2.java sortコマンドにAAAAAからZZZZZまでの文字列を標準出力で渡し、結果を標準入力から受け取る。
・RunTimeの実行をスレッドで行っています。
・convertコマンドの構造によっては、入出力の処理をThreadにする必要があるかもしれません。
以下が、ExecCommand2.javaのソースです。
久しぶりに、Javaで書きました。
import java.io.*;
public class ExecCommand2 extends Thread {
String com;
Process ps;
public ExecCommand2(String com) throws Exception {
this.com = com;
}
InputStream getInputStream() throws Exception {
return ps.getInputStream();
}
OutputStream getOutputStream() throws Exception {
return ps.getOutputStream();
}
public void run(){
try {
ps = Runtime.getRuntime().exec(com);
} catch (Exception e) {};
}
public static void main(String args[]) throws Exception {
OutputStream os;
InputStream is;
int c;
System.out.println(”Start”);
//ExecCommand ex = new ExecCommand(”/windows/system32/hostname”);
//ExecCommand ex = new ExecCommand(”convert -resize 32x32 - -”);
ExecCommand2 ex = new ExecCommand2(”sort /R”);
ex.start();
// なぜか必要、プロセスの初期化の時間?
Thread.sleep(2000);
os = ex.getOutputStream();
is = ex.getInputStream();
for ( c = ’A’; c <= ’Z’; c++) {
//AAAAA改行からZZZZZ改行を出力
os.write(c);
os.write(c);
os.write(c);
os.write(c);
os.write(c);
os.write(0x0d);
os.write(0x0a);
}
os.close();
while ( (c = is.read()) != -1){
System.out.print((char)c);
}
is.close();
//BufferedOutputStream std_in = new BufferedOutputStream(os);
//byte[] buf = new byte[1000];
//int m;
//while ((m = is.read(buf)) > 0)
//std_in.write(buf, 0, m);
//is.close();
}
}
ありがとうございます!
ありがとうございます!
ps = rt.exec(”convert -resize 32x32 - -”);
の前にconvertに渡す第一引数に当たるものをパイプで渡したいのです。
よろしくお願いいたします。