ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 写入控制台和文本文件

2019-09-19 02:03:20  阅读:243  来源: 互联网

标签:fileoutputstream java console file-io printstream


我从互联网上找到了下面的代码,但它不会将打印的控制台写入omt.txt,它只会在第二个catch块之后写入System.out.println语句.如果你运行代码,你会明白什么我的意思是.我想要的是将控制台上的内容写入“omt.txt”文件,这些文件都是……

经过一些回答,我发现我的问题不明确,对不起.
我想将控制台输出保存到omt.txt文本文件中.如果在控制台上打印“Hello 123”,它也应该在omt.txt文件中.换句话说,打印控制台上的任何内容都应该同时写在om.txt文件中,或者可以在控制台执行后但是应该是1对1相同!

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

public class Wrt_file {

    public static void main(String[] args) {
        System.out.println("THIS is what I see on the console. but not on TEXT file"); 

          File f = new File("omt.txt");
          if(!f.exists())
          {
            try {
                       f.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
          }

        try {
                FileOutputStream fos = new FileOutputStream(f);
                PrintStream ps = new PrintStream(fos);
                System.setOut(ps);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("THIS is what I see on the text file, but not on CONSOLE");      

        for (int i=0; i<10; i++){

            System.out.println("Testing");  
        }

    }

}

解决方法:

在得知OP想要复制流之后更新了答案

由于您要在两个流中写入数据,请尝试使用TeeOutputStream中的TeeOutputStream.在第二次尝试更改您的代码

try {
    FileOutputStream fos = new FileOutputStream(f);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            fos.flush();
        }
        catch (Throwable t) {
            // Ignore
        }
    }, "Shutdown hook Thread flushing " + f));
    //we will want to print in standard "System.out" and in "file"
    TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
    PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
    System.setOut(ps);
} catch (Exception e) {
    e.printStackTrace();
}

现在,System.out的结果也将放在您的文件中.

标签:fileoutputstream,java,console,file-io,printstream
来源: https://codeday.me/bug/20190919/1812059.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有