0

I'm working on a big Java project right now, and I decided that the easiest way to "fix" an issue I have with the data in a File object would be to parse and edit it with a Python script I wrote. I tested the Python script on its own on this particular file (outside of Java) and it works fine. Now I'm just wondering how I integrate my Python script with the rest of my Java code.

I basically want to somehow pass this File object to my Python script, which has to be called from Java. Then I want to take the file that the Python script outputs, read it back in as a File object, and return that from this particular Java method.

From researching a bit, I've heard Jython come up a bit, as well as the built-in Python interpreter in Java 6 and later. I'm just not sure where to start. Or alternatively, I guess I could port this Python script over to Java, but that's kind of a last resort. Any help is appreciated!

7
  • 1
    Why don't you program it in one language? Sounds to me like you're overcomplicating the things here. Commented Mar 4, 2014 at 21:50
  • 1
    I agree. You should do one language. if this is not an option you could use a Process to execute a different command on your OS firing off your python change. This is not OS independent though and can be directly affected by your environment running the application. Commented Mar 4, 2014 at 21:52
  • Look at these classes docs.oracle.com/javase/7/docs/api/java/lang/Process.html docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html But I think you'd better do it in just one language. Commented Mar 4, 2014 at 21:53
  • 1
    @peter.petrov "Why don't you program it in one language?" If the script was already there, it'd rather be an overcomplication to rewrite it in Java. Commented Mar 4, 2014 at 21:53
  • 1
    Is there a reason you want to pass the "File object" around specifically? A more standard workflow would be to invoke the python interpreter from Java, have the python script write the file somewhere and then exit, with your java program then reading the file in. Commented Mar 4, 2014 at 21:53

1 Answer 1

1

Look at these classes

http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

You can use them in Java to call your Python process.

Sign up to request clarification or add additional context in comments.

1 Comment

Especially note Process#getOutputStream() and Process#getInputStream(). You can communicate with the script through those channels (they are represented as sys.stdout and sys.stdin on the Python side)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.