Matlab exe 无法读取在 Java 中创建的文件

Matlab exe unable to read a file created in Java

我的目标是从 Java 程序执行 Matlab 可执行文件。为了测试这种机制,我有一个 Java 程序,它接受输入并将值写入文件。 Matlab .exe 被编程为读取文件并显示内容。 (一旦一切正常,我将继续进行主要的 Matlab 操作)。

但不幸的是,我无法使用 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 生成了 exe

mcc -mv myfunc1.m

当我在 matlab 命令提示符下执行 !myfunc1.exe 时,它工作正常。当我删除文件操作并使用 myfunc1.exe 简单地打印一个字符串时,它在从 Java 调用时工作正常。 我无法确定为什么 Java 程序无法触发 Matlab .exe 中的文件读取操作

尝试将您的 Matlab 函数修改为:

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