2 Replies - 272 Views - Last Post: 07 June 2014 - 02:12 PM Rate Topic: -----

#1 rishabhsharma  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 10
  • View blog
  • Posts: 342
  • Joined: 26-March 09

Input/Output using Process class

Posted 06 June 2014 - 10:31 AM

I want to do basic input/output using Process class.
I basically wish that, I should ask user his name and when user provides his name then I would print "Hello '[name]'"

import java.io.*;

public class ReadAndPrintName
	{
		static Process p;
		public static void main(String[] args)
			{
				try
					{
						runProcess("javac Main.java") ;
						runProcess("java Main") ;
					}
				catch(Exception e)
					{
						e.printStackTrace() ;
						System.out.println(e) ;
					}
			}
		public static void runProcess(String cmd)throws Exception
			{
				p = Runtime.getRuntime().exec(cmd) ;
				printLines(p.getInputStream()) ;
				giveInput("Rishabh") ;
				printLines(p.getErrorStream()) ;
			}
		public static void giveInput(String str)throws Exception
			{
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())) ;
				bw.write("Rishabh") ;
			}
		public static void printLines(InputStream ins)throws Exception
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(ins)) ;
				String a = "" ;
				while((a = br.readLine()) != null)
					System.out.println(a) ;
			}
	}



import java.io.*;
public class Main {
  public static void main(String[] args)throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;
		
		System.out.println("Please Input Your Name : ") ;
		String name = br.readLine() ;
		
		System.out.println("Hello "+name+" !!!") ;
	}
}



But I am not able to provide input. Where am I doing wrong?

This post has been edited by rishabhsharma: 06 June 2014 - 10:57 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Input/Output using Process class

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2650
  • View blog
  • Posts: 11,181
  • Joined: 20-September 08

Re: Input/Output using Process class

Posted 06 June 2014 - 04:49 PM

Quote

           giveInput("Rishabh") ;


Change that to

System.out.println("Now asking for input ...");
giveInput("Rishabh") ;

Does that print? If not, then the previous call is probably blocking. You normally need to treat Process streams in separate threads. See and http://technojeeves..../13-runtimeexec
links therein
Was This Post Helpful? 0
  • +
  • -

#3 SuperProgrammer  Icon User is offline

  • New D.I.C Head

Reputation: 10
  • View blog
  • Posts: 46
  • Joined: 17-April 14

Re: Input/Output using Process class

Posted 07 June 2014 - 02:12 PM

Use a scanner to make it easier for you :smile2: .
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1