Results 1 to 2 of 2

Thread: nio and getRuntime()

  1. #1
    Contributing Member
    Join Date
    Sep 2006
    Answers
    962

    nio and getRuntime()

    Does anybody have an example of using nio channels or bytebuffers to read stdout/stderr of a command run with getRuntime?

    ----------------------
    suresh


  2. #2
    Contributing Member
    Join Date
    Sep 2006
    Answers
    962

    Re: nio and getRuntime()

    I am using Runtime.exec() to compile a .c file with gcc. Sample program is

    Code:
    /**	 * Call the <strong>gcc</strong> compiler. Create two {@link EiffelFileReader.StreamEater} objects which	 * put all the messages from it into {@link List} objects for printing later if necessary.	 */	public void compile()	{		List<String> errorList, outputList;		errorList = new ArrayList<String>(3);		outputList = new ArrayList<String>(3);		int endIndex, returnValue;		String filePath, fileName;		String instruction = "gcc -o ";		try		{			fileName = outputFile.getCanonicalPath();			endIndex = fileName.lastIndexOf(File.separator);			filePath = fileName.substring(0, endIndex + 1);			instruction += filePath;			instruction += JOptionPane.showInputDialog(null,					"Please enter Name for output File.\n\".exe\" added automatically in Windows"					+ "\nThe same directory will be used as for the \".c\" file.",					"Output", JOptionPane.QUESTION_MESSAGE);			if (System.getProperty("os.name").toLowerCase().contains("windows"))			{				instruction += ".exe";			} // end if System.getProperty("OS").toLowerCase().contains("win")			instruction += " ";			instruction += fileName;						Runtime run = Runtime.getRuntime();			Process myProcess = run.exec(instruction);			/*			 * You need to redirect the output and error streams from the process.			 */			new StreamEater(myProcess.getErrorStream(), errorList).start();			new StreamEater(myProcess.getInputStream(), outputList).start();			/*	Allow a 1-second delay to make sure the previous Threads have completed.	*/			returnValue = myProcess.waitFor();			Thread.sleep(1000);			if (returnValue == 0)			{				out.printf("No errors reported%s%n",						errorList.size() > 0 ? ". There are warnings however." : ".");			} // end if returnValue == 0			else			{				out.printf("Returned with a value of %d%n", returnValue);			} // end else			out.println("<OUTPUT>");			for (String string : outputList)			{				out.println(string);			} // end for-each			out.println("</OUTPUT>");			out.println("<ERRORS>");			for (String string : errorList)			{				out.println(string);			} // end for-each			out.println("</ERRORS>");		}//end try		catch (IOException exc)		{			err.println("Error occurred trying to find the files");			exc.printStackTrace(err);		} // end catch IOException		catch (InterruptedException exc)		{			exc.printStackTrace(err);		}	}//end compile . . .	/**	 * This class takes all the messages from a particular {@link InputStream} using	 * a {@link Scanner} and puts them into a {@link List} so they can be printed later.	 * This is necessary because the {@link Runtime#exec(String)} method takes a little	 * time to operate, and its output streams have to be diverted.	 * <a href=http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4>M C Daconta	 * <i>When Runtime.exec() won't</i> Javaworld magazine, 29th September 2000.</a>	 * @author Campbell	 *	 */	private class StreamEater extends Thread	{		/**		 * A {@link List} which the output is put into		 */		private List<String> myList;		/**		 * An {@link InputStream} which is diverted to this class		 */		private InputStream myStream;		/**		 * A {@link Scanner} which readds from the {@link InputStream}.		 */		private Scanner myScan;				/**		 * Create an object of {@link EiffelFileReader.StreamEater}.		 * @param myStream	The {@link InputStream} used by this StreamEater		 * @param myList	The {@link List} which the output is put into		 */		public StreamEater(InputStream myStream, List<String> myList)		{			super();			this.myStream = myStream;			this.myList = myList;		}//end constructor				/**		 * Opens the {@link InputStream} with a {@link Scanner} and reads all the output		 * into the {@link List} object passed. Then closes the {@link Scanner} and handles		 * any {@link IOException} which might have occurred.		 */		@Override		public void run()		{			try			{				try				{					myScan = new Scanner(myStream);					while(myScan.hasNext())						myList.add(myScan.nextLine());					if (myScan.ioException() != null)					{						throw myScan.ioException();					} // end if myScan.ioException() != null				} // end try				finally				{					if (myScan != null)					{						myScan.close();					} // end if myScan != null// Fill in finally block, close reader, etc				} // end finally			} // end try			catch (IOException exc)			{				System.err.printf("Error occurred trying to read output from Runtime.exec()%n");				exc.printStackTrace(err);			} // end catch IOException		}//end run	}//end private stream eater class}//end class



Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact