2016-05-13 86 views
0

我的目標是從Java程序執行Matlab可執行文件。爲了測試這種機制,我有一個Java程序,它接受輸入並將值寫入文件。 Matlab .exe被編程爲讀取文件並顯示內容。 (一旦這個工作正常,我將繼續主要的Matlab操作)。Matlab exe無法讀取在Java中創建的文件

但不幸的是,我無法使用Matlab可執行文件打印文件的內容。 這是我的Java代碼。

public class JavaMatlab_I_O 
{ 
    public void MatlabexeCall(String commandline) 
    { 
     try 
     { 
      String line; 
      Process p = Runtime.getRuntime().exec(commandline); 
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      while ((line = input.readLine()) != null) 
      { 
       System.out.println(line); 
      } 
      input.close(); 
     } 
     catch (Exception err) 
     { 
      err.printStackTrace(); 
     } 
    } 
    public static void main(String[] args) 
    { 
     FileOutputStream fop = null; 
     File file; 
     String inp; 
     System.out.println("Enter Data: "); 
     Scanner obj = new Scanner(System.in); 
     inp = obj.next(); 
     try 
     { 
      file = new File("C:\\Users\\PritamDash\\Documents\\MATLAB\\TestFile2.txt"); 
      fop = new FileOutputStream(file); 
      // if file doesnt exists, then create it 
      if (!file.exists()) 
      { 
       file.createNewFile(); 
      } 

      // get the content in bytes 
      byte[] contentInBytes = inp.getBytes(); 
      fop.write(contentInBytes); 
      fop.flush(); 
      fop.close(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     JavaMatlab_I_O test = new JavaMatlab_I_O(); 
     test.MatlabexeCall("C:\\Users\\PritamDash\\Documents\\MATLAB\\myfunc1.exe"); 

     System.out.println("Done"); 
    } 
} 

Matlab代碼

function myfunc1() 
    disp(importdata('TestFile2.txt')); 
end 

我使用MCC

mcc -mv myfunc1.m 

當我在MATLAB命令執行!myfunc1.exe提示它工作正常生成的exe。當我刪除文件操作並使用myfunc1.exe來簡單打印字符串時,從Java調用時它工作正常。 我無法確定爲什麼Java程序是無法觸發文件讀取Matlab中運行.exe文件

+0

這工作。感謝您的建議。 – Pritam

回答

0

嘗試修改您的MATLAB函數:

disp(importdata('C:\Users\PritamDash\Documents\MATLAB\TestFile2.txt')); 
+0

但是,如果我在另一臺機器上執行相同的.exe它不會工作。由於路徑是靜態的。 – Pritam

+0

您可以創建文本文件到Java中的固定路徑,然後您可以使用該路徑。我的意思是如果你使用例如C:\ yourdirectory \ xyz.txt,它應該存在。 這真的取決於你的用例。 以編程方式獲取用戶目錄的另一種可能性,爲此,此線程可以提供幫助:https://de.mathworks.com/matlabcentral/newsreader/view_thread/149027 – DVarga

+0

這個看起來很有趣。謝謝你的時間。! – Pritam