Java:打印到控制台和文件 [英] Java: Printing to the console and to a file

查看:371
本文介绍了Java:打印到控制台和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点问题

我正在运行一个包含许多类的程序,并使用一个驱动程序来运行所有这些类.运行驱动程序时,输出可以在控制台上很好地打印,但是我还需要控制台上的确切输出才能打印到文件中.

I am running a program with many classes, with one driver to run all these classes. When I run the driver, the output prints on the console just fine, but I also need the exact output from the console to be printed to a file.

但是,我似乎无法获得控制台输出以打印到文件中.我在这里尝试过该建议

However, I can't seem to get the console output to print to a file. I have tried the suggestion here

如何将控制台输出写入txt文件

这样做

import java.io.FileOutputStream;
import java.io.PrintStream;



public class Compiler {
    public static void main(String args[]){
        try {

            Parse parser = new Parse();
            SemanticAnalyzer sAnalyzer = new SemanticAnalyzer();
            String parserfile= parser.parsefile(args[0]);
            sAnalyzer.semanticAnalysis(parserfile);
            PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
            System.setOut(out);

        } catch (Exception e) {

            e.printStackTrace();
        }


    }
}

但是文件仍然空白(也许是因为打印语句在其他文件中?).

but the file still comes out blank (perhaps because the print statements are in other files?).

有人有什么想法吗?

推荐答案

我确定在输入完之前会得到回答...但是这里发生的是您正在从控制台重定向(默认)输出流到一个文件.如果要打印到两个位置,则需要有一个实际上记录到两个位置的PrintStream. (或者,您可以查找一个日志记录解决方案-有几个).但是,为了对此有所了解,

I'm sure this will be answered before I finish typing... however what's happening here is you're redirecting the (default) output stream from the console to a file. If you want to print to both locations you would need to have a PrintStream that actually logs to both locations. (Or you can go look up a logging solution--there are several). However, in the interest of being mildly academic about it:

http://docs.oracle.com /javase/7/docs/api/java/io/PrintStream.html

您可以实现一个PrintStream或OutputStream(可能是更好的选择),方法是实现接口并分别记录到文件和控制台中(喜欢!).

You can implement a PrintStream or OutputStream (probably the better choice) that does this by implementing the interfaces and logging to both the file and console in each case (yikes!).

一种更简单的方法,上面由@Voicu进行了解释,但感觉有点误导了,该方法是通过创建一个新方法来替换System.out();调用,该方法将这些流指定为输出的一部分.您可以轻松创建一个静态方法来解决此问题:

The easier method, which was explained above by @Voicu but feels a bit misguided is to have a method that replaces System.out(); calls by creating a new method that specifies those streams as part of the output. You could easily create a static method to get around this:

//Redirect via a method
public static PrintStream FILE = new PrintStream(new FileOutputStream("output.txt"));

public static void log(String x)
{
  FILE.println(x);
  System.out.println(x);
}

现在,一个可怕的但实用的解决方案看起来像这样:

Now a terrible, but functional solution, would look something like this:

public static class DualStream extends PrintStream
    {
        private PrintStream out;
        private PrintStream file;

        public DualStream(File file, PrintStream out) throws FileNotFoundException
        {
            super(file);//I'm being SUPER lazy/hacky here
            this.out = out;
            this.file = new PrintStream(file);
        }

        //... through all the methods I want to use...

        public void println(String x) {
            out.println(x);
            file.println(x);
        }
    }

    public static void main(String ... args) throws FileNotFoundException
    {
        DualStream out = new DualStream(new File("output.txt"), System.out);
        System.setOut(out);

        System.out.println("This is a test");
    }

现在这是糟糕的代码,首先我违反了我的构造函数合同才能进行此工作,但 确实可行 .我根本不建议这样做,我只是想证明它是可以做到的"(如果您确实需要的话).正确的方法是使用那里的许多记录器之一,或者坦率地说,将命令行上的输出重定向到所需的位置.

Now this is terrible code, first I'm violating my constructors contract to make this work but it does work. I don't recommend doing this at all, I just wanted to prove it "can be done" if you really need it. The correct approach is to use one of the many loggers out there, or frankly, redirect the output on the command line to where you want it.

在这种情况下,您想要使用正在运行的操作系统或服务器: (如何将命令的输出重定向到两个文件) 这确实可以实现您想要的功能,但是允许用户根据需要进行登录.如果您不想使用日志记录系统(Log4J,日志记录包等)进行日志记录,那么我将把它留给您的用户使用,只使用err/out而不是过度考虑它. java -jar myjar.jar > log.txt

What you want in this case is to use the operating system or the server you're running on: (how to redirect a output of a command to two files) This does EXACTLY what you want but allows the user to log as needed. If you don't want to log using a logging system (Log4J, Logging package, etc...) then I'd leave it up to your users and just use err/out rather than overthinking it. java -jar myjar.jar > log.txt

这篇关于Java:打印到控制台和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆