简体   繁体   中英

On executing batch file capture command prompt logs and save a backup of those logs in file using Java

To print the logs in file I used the below code,, but I not able to print "System.out.println" statement which exists in batch file code.

    Runtime runtime = Runtime.getRuntime();
    Process p1 = runtime.exec("C:\\Users\\mf11131\\Desktop\\Batch\\SimpleBatch.bat");
    java.io.InputStream is = (java.io.InputStream) p1.getInputStream();
    File logfile = new File("C:\\logs\\Logfile.txt");
    FileOutputStream fop = new FileOutputStream(logfile);
    int i = 0;
    while((i = is.read()) != -1)
    {
        fop.write((char)i);
    }

Below is the simple code of batch file.

class abc
{
   public static void main(String args[])
   {
     int count=0;
     for(int i=0;i<10;i++)
     {
        System.out.println("hi hello"+count);
     }
   }
}

I need output like below command prompt logs 在此处输入图片说明

My current output is 在此处输入图片说明

If you want to get all of the output into a file you should use stream redirection like this

byBatFile.bat > logFile. 

This will cause all the output to be stored into logFile .

I have my doubts about possibility to get stdio streams of invoked applications inside batch script. I think that IO is separated in manners you would like to use it.

On the other hand, your batch script "spawns" new processes on every command. You could try to call those processes insteed of spawning new ones like this

call javac abc.java
call java abc

I found the solution for this as I done a mistake of pointing directory to Java class directory while creating a Batch file. So only Java (System.out.println) statements are not printing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM