简体   繁体   English

在执行批处理文件捕获命令提示符日志时,使用Java将这些日志的备份保存在文件中

[英]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. 要打印日志文件,我使用了以下代码,但无法打印批处理文件代码中存在的“ System.out.println”语句。

    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 . 这将导致所有输出都存储到logFile

I have my doubts about possibility to get stdio streams of invoked applications inside batch script. 我怀疑是否有可能在批处理脚本中获取被调用应用程序的stdio流。 I think that IO is separated in manners you would like to use it. 我认为IO是按照您希望使用的方式分离的。

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这些过程为生成新的过程,例如这样

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. 我找到了解决方案,因为在创建批处理文件时将目录指向Java类目录时犯了一个错误。 So only Java (System.out.println) statements are not printing. 因此,仅Java(System.out.println)语句不打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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