How to print an output stream on console.

Hi,
I am new to JAVA. I am trying to execute a command in runtime and I want to print the output on console and also redirect the output to a file.
Could anyone please help me?
This is what I wrote :
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c ipconfig");I am getting an output stream by : proc.getOutputStream(). I dont know how to print it on console and also how to redirect it to a file.
Could anyone please help me.
Thanks in advance.
Basav

You can do it this way :-
     public static void main(String args[]) throws Exception {
          ProcessBuilder builder = new ProcessBuilder("ipconfig", "/all");
          Process process = builder.start();
          BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
          FileWriter writer = new FileWriter(new File("C:/ipconfig.txt"));
          String str;
          while ((str = reader.readLine()) != null) {
               System.out.println(str);
               writer.write(str + System.getProperty("line.separator"));
          writer.close();
          reader.close();
     }Let me know if it works for you.

Similar Messages

  • Please help : How to print a matrix from the console...

    Hi..
    Please help:
    How to print a matrix on the console , but i want to take all the input from the console.. like...
    if the matrix is of size...
    mxn
    where
    m : row
    n : column
    and the all the elements of the matrix from the console it self... .
    Please help...

    Thanks...
    I am able to print the elements of the array but i am not able to assign those values to the array ....
    How to do that...
    I just did a little change in my code...
    import java.util.Scanner;
    public class CreatingAMatrix {
        public static void main(String[] args) {
         // TODO Auto-generated method stub
         System.out.print("Enter the number of rows: ");
         Scanner scanner1 = new Scanner(System.in);
         int m = scanner1.nextInt();
         System.out.print("Enter the number of coulmns:");
         Scanner scanner2 = new Scanner(System.in);
         int n = scanner2.nextInt();
         System.out.println("The size of the matrix is : " +m+" x "+n );
         int[][] a = new int[100][100];
         for(int i=0;i<=m;i++)
             for(int j =0; j <= n; j++)
              Scanner scanner3 = new Scanner(System.in);
              int o = scanner3.nextInt();
             System.out.println();
         for(int i=0;i<=m;i++)
             for(int j =0; j <= n; j++)
              System.out.print(a[i][j] + "\t");
             System.out.println();
    }I am getting an output as this
    output:
    Enter the number of rows: 2
    Enter the number of coulmns:1
    The size of the matrix is : 2 x 1
    1
    2
    1
    2
    3
    5
    0     0     
    0     0     
    0     0     
    how should i assig those input values to my array..
    Please help

  • Re : how to print report output in DOT MATRIX printer

    Hai
           how to print report output in DOT MATRIX printer.
    Thanks
    mani

    Check this
    [http://help.sap.com/saphelp_nw04/helpdata/en/90/78f078030211d399b90000e83dd9fc/frameset.htm]
    also check the SAP Note 129581

  • How to print the output of the screen in Dialog Programming

    Hi,
    Could anybody help how to print the output of a screen in the dialog programming. i can select 'Hard Copy' option in the 'Custumizing of Local Layout' Icon in the standard tool bar. but that prints the whole screen with the toolbar. i want to print only the output which is displayed on the screen. Please help..
    Regards,
    Swathi

    Hi Swathi,
        Ok. Do One thing. Go to menu bar and select Systems -> Own pool Request -> here you get the spool number. Select it and select the option "Print Directly" in tool bar.
    Thanks.

  • Tutorial on how to print  multiple output pages

    Hi,
    I am rather sad that this forum does not provide a simple principle on how to printout multiple pages to newbie.
    Below is a short contribution from me on how to print across multiple pages, other reader are also encourage to modify the code to provide more robust tutorial .
    * How to use java to print across pages that are more than one
    * Short contribution to java forum by Eric gan (Malaysia)
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.awt.Graphics2D;
    import java.awt.print.*;
    import java.awt.print.Book;
    import java.awt.print.Pageable;
    import java.awt.Graphics2D;
    import java.awt.Graphics;
    public class Example implements Printable {
    //--- Private instances declarations
    private int row_cnt=30; // set the total number of row per page
    private int cum_row_cnt=30; // set the counter to record total number of row per page to determine
    // whether maximum pages should be increase depending on the programme requirement
    private int max_pg=0; // set the maximum number of page
    public Example () {
    //--- Create a printerJob object
    PrinterJob printJob = PrinterJob.getPrinterJob ();
         printJob.setPrintable(Example.this);
    if (printJob.printDialog()) {
    try {
    printJob.print();
    } catch (Exception PrintException) {
    PrintException.printStackTrace();
    public void paint (Graphics g) {
    Graphics2D g2d;
    g2d = (Graphics2D) g;     
    int x=10;
    int y=10;
    for (int outline=0;outline<=160;outline+=20){
              if (y>cum_row_cnt){
              cum_row_cnt+=row_cnt;//counter should grow by value equal to row_cnt
         max_pg++;
         g2d.drawString("outline value ---> " +outline , x, y);
         y+=10; // to set the row printing interval      
    } // end of paint procedure
         public int print(Graphics g,
    PageFormat pf, int pi)
              throws PrinterException {
    // normal routine to check when should java stop the print looping
    if (pi >max_pg) {
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
         int fontHeight=g2.getFontMetrics().getHeight();
         int fontDesent=g2.getFontMetrics().getDescent();
         double pageHeight = pf.getImageableHeight()-fontHeight;
         double pageWidth = pf.getImageableWidth();
         // setting for the translate and graphics clipping to enable printing on output pages
    // row_cnt can be equal to pageHeight
    // in this examples assumming pageHeight=20 rows           
         g2.translate(pf.getImageableX(), pf.getImageableY());
    g2.translate(0f,-pi*row_cnt);
    g2.setClip(0, (int)(row_cnt* pi),
    (int) Math.ceil(pageWidth),
    (int) Math.ceil(row_cnt));
    paint(g2);
    return Printable.PAGE_EXISTS;
    public static void main (String [] args) {
    Example example = new Example ();
    System.exit (0);
    Thank

    Hello
    I know that Pages is using its own algorithm to resize pages when it put several of them on a single sheet.
    This is why I use this tip.
    I draw a rectangle whose size is supposed to be the final one.
    I give it a white background and a black border whose thickness is set to one point.
    For the tests I just insert three page breaks so that the document is a four pages one.
    I print it as is.
    Doing that, I may measure the printed rectangle.
    Of course, at first attempt it doesn't match the required size.
    It's easy to compute the required adjustments.
    When the correct factor is reached, it is easy to build the complete document so that it prints the correct size.
    Doing that I never got odd results but maybe it's because I am a lucky guy.
    Of course, disagreeing with one advice doesn't mean that I don't respect it.
    I respect your opinion, _on other matters too_
    Yvan KOENIG (from FRANCE mardi 6 mai 2008 17:24:09)

  • How to print this output. (Array)

    Hi all. I have two String array:
    String[] a = { "a", "b", "c", "d", "e" };
    String[] b = { "b", "d" };
    I want to print this two array into this output:
    Output:
    a
    bb
    c
    dd
    e
    Anybody can help me how to get this output. I have try with a for loop, but it's not working.

    try this,
    boolean found=false;
    for(int i=0; i<a.length;i++)
             found=false;
             for(int j=0;j<b.length;j++)
                     if(a.equals(b[j])
    found=true;
    if(found==true)
    System.out.println(a[i]+a[i]);
    else
    System.out.println(a[i]);

  • How to forward after output stream is open

    Hi
              I want ot forward one jsp page to another, but the output stream of the jsp
              page is open and content is showed.
              I know <jsp:forward> can't work now. Then what can i do?
              Thanks all
              

              You can also set autoFlush to false and increase the buffer (session). Her is an example:
              <%@ buffer="1024kb" autoFlush="false" import="java.io.*" %>
              If the buffer is full and you did not flush him, you will get an IOException.
              Robert Patrick <[email protected]> wrote:
              >It doesn't matter if the OutputStream is open, it matters whether or not
              >the
              >OutputStream has been flushed. If you are not explicitly flushing it (or
              >flushing it implicitly by using jsp:include), you might want to play around
              >with moving some of the content so that the buffer size is not exceeded
              >(which
              >causes it to be flushed) before the jsp:forward is encountered or try
              >increasing the size of the buffer...
              >
              >Hope this helps,
              >Robert
              >
              >andy wrote:
              >
              >> Hi
              >> I want ot forward one jsp page to another, but the output stream of the
              >jsp
              >> page is open and content is showed.
              >>
              >> I know <jsp:forward> can't work now. Then what can i do?
              >>
              >> Thanks all
              >
              

  • How to print from an applet to console

    Hi,
    I'm passing my applet a parameter then I'm trying to print it using System.out.println but I don't see any output. My web app is deployed in weblogic 7. From the html page I pass in applet param but I don't see any out put in weblogic console.How can I see the output. here is what I have in my html page.
    <APPLET codebase="classes" code="taqDingHILoNew.class" width=550 height=420
         archive="../../../lib/EspressAPI.jar">
    <PARAM name="cabbase" value="../../../lib/EspressAPI.cab">
    <PARAM NAME=FontName VALUE="Arial" >
    </APPLET>
    And here is code for my applet. Any help would be greatly appreciated.
    public class taqDingHILoNew extends Applet implements ActionListener{
    TextField tf;
    public static void main(String argv[]){
    taqDingHILoNew chartFrame = new taqDingHILoNew();
    Frame frame = new Frame();
    frame.setLayout(new BorderLayout());
    frame.add("Center", chartFrame.createComponent2(null));
    frame.pack();
    frame.show();
    public void init() {
    setLayout(new BorderLayout());
    String param = this.getParameter("FontName");
    System.out.println("GOT APPLET PARAM " + param);
    add("Center", createComponent2(this));
    Component createComponent2(Applet applet) {
    QbChart.setChartServerUsed(false);
    setLayout(new BorderLayout());
    // primary axis value column 3
    // secondary axis value column 2
    // ColInfo(series, category, sumby, primary_value, secondary_value)
    QbChart chart;
    String param = this.getParameter("FontName");
    System.out.println("GOT APPLET PARAM " + param);

    If you're using the java plug-in, you can right click on the java icon in that system tray to the bottom right of the screen if you've got a normal set-up. Also I think you can invoke it via the start menu.
    If you're not using the plug-in, MSIE and Netscape both have "show java console" options. However on MSIE I think you have to turn on an Advanced Option first that lets you see the "show java console" option. It's a pain.
    Of course, if it's an applet, normally you're not the one viewing the console at all. It's the user who sees it. You only get to see the client java console if you happen to be the user.

  • How to print the output string in inverted commas

    hi all,
    my question is
    like i have a string
    "welcome to java"
    using println statement
    i need to print the above statement in inverted commas
    like the output should appear as
    "welcome to java"

    This sounds like part of some homework but what the
    heck ...
    System.out.println("\\"welcome to java\\"");I was trying to anticipate bugs in this stupid forum sofftware, this should be
    System.out.println("\"welcome to java\"");

  • OEM 10G -- how to print the output of a table in a html report

    Hi everyone,
    I am trying to print the out of a particular table from the DB using OEM but having some hard time to do so, does any one know the way. Thanks for reading.
    Oracle version: 10.2
    OS: Windows xp
    Regards,
    katheri

    after login to the OEM ,
    you want the rows of the table or structure of the table?
    you can find administration tab top of the page,
    again you database objects -> tables
    new web page will open -> there you have to enter schema name and table name -> you will get the list of table and then click to view , data types and sizes and all..

  • How to print output of XML Publisher report in different trays of a printer

    Hi All,
    I have a requirement in XML Publisher Report. I need to print all pages other than last one in one tray of a printer and the last page has to be printed in another tray of the same printer.
    Can anyone help me out...
    Thank You..

    I do not think it is possible to send all the pages to one tray and send only the last page to a different tray. However, you may review the following notes:
    Note: 357402.1 - How to Print the Output to a Different Paper Size Using XML Publisher Delivery Manager?
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=357402.1
    Note: 394130.1 - How To Enable Printer Options Such As Duplex Printing Or Tray Selections For Bitmap Concurrent Programs
    https://metalink2.oracle.com/metalink/plsql/ml2_documents.showDocument?p_database_id=NOT&p_id=394130.1

  • How to print a HTML file in browser look using DocPrintJob

    Hello guys,
    Does anyone know how to print HTML output/file into browser look?
    I'm using DocPrintJob and the DocFlavor set to DocFlavor.INPUT_STREAM.AUTOSENSE.
    posted below is my code :
    public class BasicPrint {
        public static void main(String[] args) {
            try {
                // Open the image file
                String testData = "C:/new_page_1.html";
                InputStream is = new BufferedInputStream(new FileInputStream(testData));
                DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE;
                // Find the default service
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                System.out.println(service);
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc= new SimpleDoc(is, flavor, null);
                // Monitor print job events; for the implementation of PrintJobWatcher,
                // see e702 Determining When a Print Job Has Finished
                PrintJobWatcher pjDone = new PrintJobWatcher(job);
                // Print it
                job.print(doc, null);
                // Wait for the print job to be done
                pjDone.waitForDone();
                // It is now safe to close the input stream
                is.close();
            } catch (PrintException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        static class PrintJobWatcher {
            // true iff it is safe to close the print job's input stream
            boolean done = false;
            PrintJobWatcher(DocPrintJob job) {
                // Add a listener to the print job
                job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobCanceled(PrintJobEvent pje) {
                        allDone();
                    public void printJobCompleted(PrintJobEvent pje) {
                        allDone();
                    public void printJobFailed(PrintJobEvent pje) {
                        allDone();
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                        allDone();
                    void allDone() {
                        synchronized (PrintJobWatcher.this) {
                            done = true;
                            PrintJobWatcher.this.notify();
            public synchronized void waitForDone() {
                try {
                    while (!done) {
                        wait();
                } catch (InterruptedException e) {
    }the printed ouput for this code will be look like this
    <html>
    <body>
    <div style="page-break-after:'always';
                background-color:#EEEEEE;
                width:400;
                height:70">
         testPrint</div>
    ABCDEFGHIJK<p>
     </p>
    </body>
    </html>however, the output that i want is the HTML in browser look not HTML code itself.
    i've tried to change the DocFlavor into any TEXT_HTML type but it gives error:
    sun.print.PrintJobFlavorException: invalid flavor if you guys has any idea or solution, can you share with me... already search in Google but still not found any solution
    Thanks in advanced.

    hi,
    do the following
    URL url = null;
    try
         url = new URL("http://www.xyz.com");
    catch (MalformedURLException e)
          System.out.println("URL not correct " + e.toString());
    if (url != null)
           getAppletContext().showDocument(url,"_blank"); //shows the page in a new unnamed top level browser instance.
    }hope that helpz
    cheerz
    ynkrish

  • Servlet Output Streams and clearing

    I am using servlets, and I want to be able to print something repeatedly. Well, that's not exactly true: I can print something repeatedly. Using a ServletOutputStream, it doesn't seem possible to clear what has already been written. Here's the code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.io.*;
    public class AlwaysTime extends HttpServlet {
         public void doPost(HttpServletRequest req, HttpServletResponse res)                throws ServletException, IOException {
              HttpServletResponse oldRes = res;
              Date now = new Date();
              res.setContentType("text/html");
              ServletOutputStream out = res.getOutputStream();
              out.println("<html>");
              out.println("<head>");
              out.println("<title>Clock</title>");
              out.println("</head>");
              out.println("<body>");
              out.println("<h1 align=\"Center\">");
              out.println(now.toString());
              out.println("</h1>");
              out.println("</body>");
              out.println("</html>");
              try {
                 Thread.sleep(1000);
              } catch (InterruptedException ie) {}
              // Do nothing: wait for 1 second.
              doPost(req, oldRes);
         public void doGet(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {
              doPost(req, res);
    }This code prints the time every second, but I want to clear the previous output stream. I thought the code shown above would work, but of course, oldRes points to the same object as res. But I don't know how to clear an output stream, so that it is completely empty. Instead, each of the new lines are appended to the same output stream.
    This doesn't only apply to servlet output streams: is there some way to clear the System output stream, for instance?
    But mainly the servlet output stream ...

    You would not want to use HTTP for this type of functionality. HTTP is known as a 'stateless' protocol that simply returns one exact response for each request. So, there is not way to 'clear' the stream (technically, you would not do so for 'normal' streams either, but when you add HTTP into the mix, the task is definitely not possible).
    You could implement the above using a RSS feed, or by using HTTP meta-refresh tags on the page itself ot resubmit the requests every second (though this would be inefficient). An applet would also do the task.
    - Saish

  • In cursor i have two queries where put the condition and how to print the d

    hi i have 2 tables 1 is emp(empid,empname,dept,grade)
    2 is salary(grade,salary)
    in cursor when ever grade is increased salary automatically increased
    in 2 diffrent queries where i will put the if condition and how to print the output.
    any one can please suggest me.
    finally my required out put is
    empid,empname,grade,salary
    thanks

    It is always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Java Sockets and Output Streams

    Hi All,
    I am beginning sockets programming and I have a problem. If there is a server listening in the background for incoming connections and say for example 4 client programs programs which we shall call client1...client4 connect. How best can I capture the output streams associated with these newly created sockets so that the server can send back isome nformation to say clients1 and client4 only which is not seen by clients 2 and 3. Similarly I would like the server to send some infor to clients 2 and 3 only which is not seen by client1 and client 4.
    Currently I have the server listening part as shown below, but not too sure how to add DISTINCT output streams for 1 and 4 on one hand and 2 and 3 on the other.
    Thanks:
    // bind socket to a port number
    ServerSocket serverSocket = new ServerSocket(portNo);
    // create socket to listen to client connection
    while (true) {
    //listen to an incoming connection
    System.out.println("chatroom server waiting for incoming connections");
    Socket incomingSocket = serverSocket.accept();
    //launch new thread to take care of new connection
    chatRoomThread chatThread = new chatRoomThread(incomingSocket);
    chatThread.start();
    //go back and wait for next connection
    Please help.
    Thanks,
    Bleak

    HouseofHunger wrote:
    yes thats exactly the way I have my in and out streams, in the run method, but that doesn't help me in filtering traffic, in other words I am saying 2 clients, client1 and client4 for example should share a common in and out stream so that they will see eact other's messages... makes sense.....?No, doesn't make sense. That's the wrong design. Each socket should have its own input and output stream (yes, I know, that's been said several times before). If messages going to client1 should also be sent to client4, then whatever writes the messages to client1's output stream must also write them to client4's output stream. Trying to make those two output streams actually be the same output stream is the wrong way to do that. Just have the controller send the messages to whoever is supposed to get them.

Maybe you are looking for

  • AttachMovie is shown on debugger but not on play

    I'm using the tutorial XML photo gallery with thumbnail from http://www.kirupa.com/developer/mx2004/thumbnails.htm I'v added code to deal when the image is not aviliable I attach a symbol with Text instead to the thumbnail and to the photo as well th

  • Can't download cover art

    No matter how mainstream the album is, iTunes fails to fetch its cover art. In fact, when I right click on an album and click on "show on iTunes store", it just says "No results for Massive Attack Mezzanine Angel", for example. FWIW, I -am- connected

  • JDeveloper J2ME "Configure The Extension" viewlet error

    The "Configure The Extension" viewlet on the following page doesn't work. http://otn.oracle.com/products/jdev/htdocs/partners/addins/exchange/j2me/index.html The error message from the JRE console is: "http://otn.oracle.com/products/jdev/htdocs/partn

  • Logging Format like in default trace

    Hi all, When using log-viewer service in visual admin I want my logs to be formatted as it is in default trace (defaultTrace.trc) The message is separately displayed in its own column whereas location/severity/date etc. is shown in its own column, bu

  • Rate Comparison query

    Table Structure Po_no number(12) Item_code varchar210), rate number(12,3)I want to output like that Item_code         Current Rate            Previous RateWhere current rate = rate of Max(po_no) and Previous Rate = rate of 2nd Max(po_no)