Pritam Pritam - 6 months ago 13
Java Question

Matlab exe unable to read a file created in Java

My goal is to execute Matlab executables from a Java program. To test this mechanism I have a Java program that takes input and writes the values to a file. The Matlab .exe is programmed to read the file and display the content. (Once this works fine I will proceed with major Matlab operations).

But unfortunately, I am unable the print the content of the file using the Matlab executable.
Here is my Java code.

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 code

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


I generated exe using mcc

mcc -mv myfunc1.m


When I execute
!myfunc1.exe
in matlab command prompt it works fine. When I remove the file operation and use myfunc1.exe to simply print a String it works fine when called from Java.
I am unable to identify why Java Program is unable to trigger the file read operation in Matlab .exe

Answer

Try to modify your Matlab function to:

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