我的目標是從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文件
這工作。感謝您的建議。 – Pritam