我正在从 Java 调用 Python 程序,因此:
String[] command = {"python.exe", "script.py", fileIn};
ProcessBuilder probuilder = new ProcessBuilder(command);
Process process = probuilder.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(process.getInputStream()));
其中 fileIn 是一个字符串。
效果很好,但现在我需要传递一个 MultipartFile(即一个文件,而不仅仅是它的名称),但我不知道如何将它传递给 Python。
最佳答案
如果您的多部分文件是 Spring 类,那么他们有一些方便的方法将文件保存到磁盘。
import java.nio.file.Path;
import java.nio.file.Paths;
...
MultipartFile file =...;
Path tempFolder = ...;
Path tempFile = Paths.get(tempFolder.toString(), file.getName());
file.transferTo(tempFile);
//now the tempFile should have the data.
String[] commands = {"python.exe", "script.py", tempFile.toAbsolutePath().toString()};
这应该使用文件名创建一个文件,并将其保存在文件夹中,然后以文件路径作为参数启动 python。
需要说明的是,...
表示我不知道的代码。我不知道您是如何创建 MultipartFile 的,也不知道您希望临时文件夹放在哪里。出于测试目的,您可以使用 Path tempFolder = Paths.get(".");
或相关内容。我还假设多部分文件是 Spring 类 org.springframework.web.multipart.MultipartFile
关于java - 如何将 MultipartFile 从 Java 传递到 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901592/