2016-04-04 69 views
0

我已經檢查了很多關於運行外部程序的線程,但他們無法解決我的問題。 運行午睡(DFT計算),我不得不使用這樣的事情(Si.fdf是輸入文件): 午睡< Si.fdf 我使用這個代碼:由java運行外部程序(Siesta)

public static void main(String argv[]) throws IOException { 

Runtime r = Runtime.getRuntime(); 
Process p;  
BufferedReader is; 
String line; 

System.out.println("siesta < Si.fdf"); 
p = r.exec("siesta < Si.fdf"); 

System.out.println("In Main after exec"); 
is = new BufferedReader(new InputStreamReader(p.getInputStream())); 

while ((line = is.readLine()) != null) 
    System.out.println(line); 

System.out.println("In Main after EOF"); 
System.out.flush(); 
try { 
    p.waitFor(); 
} catch (InterruptedException e) { 
    System.err.println(e); // 
    return; 
} 
System.err.println("Process done, exit status was " + p.exitValue()); 
return; 

}

但這段代碼只運行Siesta,沒有任何輸入文件。

+0

您正在通過'p.getInputStream()'讀取子進程的'stdout'。你需要通過'p.getOutputStream()'將你的數據提供給子進程的'stdin'。將'

+0

我已經使用了 OutputStream out = p.getOutputStream(); out.write(「 user3578884

+0

我的意思是你應該把你的輸入文件的**內容**寫入你的子進程的'stdin'中。你通過讓Bash爲你工作解決了你的問題; Bash理解字符「<」作爲讀取輸入文件並將其內容寫入Siesta的「stdin」的指令。 Java不像這樣解釋'<'字符,它不是Unix shell。爲了在Java中實現相同的功能,您必須重新創建Bash的功能:讀取輸入文件的內容,並將其推入子進程的「stdin」中。 –

回答

0

最後我解決了這個問題。我向終端添加一個批處理文件,程序控制它的內容。通過運行這個批處理文件解決了問題。

public static void writeBatchFile(String batchFileName, String fileName, String inputFile) throws Exception{ 
    FileWriter write = new FileWriter(batchFileName); 
    PrintWriter print_line = new PrintWriter(write); 
    print_line.println("#!/bin/bash"); 
    print_line.println("siesta < "+ inputFile +".fdf"+ " > " + fileName + ".out"); 
    print_line.close(); 
}