Read and Write Python scripts in JAVA
Compile a tool class for reading Python.
Import org. python. util. pythonInterpreter; import java. io. fileInputStream; import java. io. IOException; import java. io. inputStream; import java. util. arrayList; import java. util. list; import java. util. map; import org. python. core. pyObject; public final class JythonUtil {private JythonUtil () {}/ *** execute. py file * @ param filePath * @ throws IOException */public static void pythonExecute (String filePath) throws IOException {PythonInterpreter pin = new PythonInterpreter (); InputStream is = new FileInputStream (filePath ); pin.exe cfile (is); is. close ();} /*** get the variable value of the python Program * @ param filePath * @ param ponames * @ return * @ throws IOException */public static List <PyObject> transP2JData (String filePath, string... ponames) throws IOException {PythonInterpreter pin = new PythonInterpreter (); InputStream is = new FileInputStream (filePath); pin.exe cfile (is); is. close (); List <PyObject> pos = new ArrayList (); for (String poname: ponames) {PyObject po = pin. get (poname); pos. add (po) ;}return pos ;} /*** assign the parameter to the python program for execution * @ param filePath * @ param pomaps * @ throws IOException */public static void transJ2PData (String filePath, Map <String, object> pomaps) throws IOException {PythonInterpreter pin = new PythonInterpreter (); InputStream is = new FileInputStream (filePath); for (String pomapkey: pomaps. keySet () {pin. set (pomapkey, pomaps. get (pomapkey);} pin.exe cfile (is); is. close ();}/*** assign the parameter to the python program for execution, obtain the variable value * @ param filePath * @ param pomaps * @ param ponames * @ return * @ throws IOException */public static List <PyObject> transJ2PData (String filePath, map <String, Object> pomaps, String... ponames) throws IOException {PythonInterpreter pin = new PythonInterpreter (); InputStream is = new FileInputStream (filePath); for (String pomapkey: pomaps. keySet () {pin. set (pomapkey, pomaps. get (pomapkey);} pin.exe cfile (is); is. close (); List <PyObject> pos = new ArrayList (); for (String poname: ponames) {PyObject po = pin. get (poname); pos. add (po) ;}return pos ;}}
Test whether the python script that calls *. py can be used
Import java. io. IOException; public class JythonUtilTest {/*** @ param args */public static void main (String [] args) {String path = "E: \ PythonScript \ hello. py "; try {// execute through the pythonexecute method of the tool class *. py script, passed in the file path JythonUtil. pythonExecute (path); System. out. println ("executed successfully");} catch (IOException e) {e. printStackTrace ();}}