1

I am having an issue trying to write to stdin from java.

here is my python code which would be receiving the stdin input

import sys 
data = sys.stdin.readlines()
print data 

I am trying to write out to stdout in java but it keeps on printing to console.

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
out.write("i am writing to stdin");
out.flush();

However it keeps on printing in java console instead of the python shell.

4
  • Are you starting the Java process from the Python program or the other way around ? Commented Feb 3, 2015 at 7:23
  • @Titus is there a way i could start the java process from python? Commented Feb 3, 2015 at 7:25
  • yes, you can use subprocess Commented Feb 3, 2015 at 7:33
  • I don't know much about Python but a quick search revealed this. Once you start the Java process you can get its output stream and read it in the Python program. Commented Feb 3, 2015 at 7:33

1 Answer 1

1

So if you want to redirect a programs stdout to an other programs stdin you usually use a pipe when calling them from shell. Here's an example scenario with your code that does this:

Java side (file called App.java):

import java.io.*;

public class App{
    public static void main(String[] args) throws Exception{
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
        out.write("i am writing to stdin");
        out.flush();
    }
}

Python side (file called App.py):

#!/usr/bin/env python
import sys 
data = sys.stdin.readlines()
print data 

Then on the shell:

First compile the java app:

javac App.java 

Then call them with a pipe:

java App | ./App.py

This will result in the output:

['i am writing to stdin']
Sign up to request clarification or add additional context in comments.

Comments

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.