问题描述
我想将Java控制台输出(由 System.out.println
及其产品生成)管道传输到文件中。我找到了一个很好的解决方案来启用Java跟踪,但这对我不起作用(没有日志文件显示在Mac OS X或Windows上的任何位置)。据我所知,这是因为我使用的是没有Java Web启动的普通Java应用程序。那么我怎么能用不使用Java web start的Java代码呢?理想情况下,我想要一个不需要修改代码的解决方案。
I am wanting to pipe the Java console output (generated by System.out.println
and its ilk) to a file. I found an excellent solution here to enable Java tracing, but this isn't working for me (no log file shows up in any location on Mac OS X or Windows). From what I can tell, this is because I'm using a plain Java app without Java web start. So how can I do this with Java code that does not use Java web start? Ideally, I would like a solution that does not require modifying code.
推荐答案
你不需要Java web start来做任何事情。这个的。只需将 System.out
设置为 FileOutputStream
。
You don't require Java web start to do any of this. Just set the System.out
to a FileOutputStream
.
System.setOut(new PrintStream(new FileOutputStream(fileName)));
其中 fileName
是该路径的完整路径你想要管道的文件。
where fileName
is the full path to the file you want to pipe to.
public static void main(String[] args) throws Exception { //Read user input into the array
System.setOut(new PrintStream(new FileOutputStream("home.txt")));
System.out.println("hello");
}
将写入 hello \ n
到当前工作目录中名为 home.txt
的文件。
Will write hello\n
to a file named home.txt
in the current working directory.
如果你不能修改代码,在Windows 7上,使用。
If you can't modify code, on Windows 7, use command redirection.
java YourMainClass > home.txt
如果你需要运行一个jar,你可以使用 -jar
。
If you need to run a jar, you can use the -jar
option of the java application launcher.
java -jar /your/path.jar > /output/file/path.txt
这篇关于如何在没有Java Web Start的情况下将Java控制台输出传递给文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!