欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java重定向程序的标准输出System.out到文件,重定向system.out,如果想将java程序的控

来源: javaer 分享于  点击 5550 次 点评:230

java重定向程序的标准输出System.out到文件,重定向system.out,如果想将java程序的控


如果想将java程序的控制台输出打印到文件,需要调用System类的setOut()方法,此方法接受一个PrintStream对象作为参数。

如下实例代码,将程序的标准输出重定向到文件流中。

import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.PrintStream;/** * Main.java * * @author byrx.net */public class Main {    /**     * 将System.out重定向到文件     *     */    public void redirectSystemOut() {        try {            System.setOut(new PrintStream(new FileOutputStream("system_out.txt")));        } catch (FileNotFoundException ex) {            ex.printStackTrace();            return;        }        System.out.println("This won't get displayed on the console, but sent to the file system_out.txt");    }    /**     * 启动程序     *     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().redirectSystemOut();    }}
相关栏目:

用户点评