为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕侠2389804 2019-09-20 17:12:32
我试图使用此代码建议(http://www.daniweb.com/forums/thread23883.html#)将控制台输出写入txt文件但是我没有成功。怎么了?try {      //create a buffered reader that connects to the console, we use it so we can read lines      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));      //read a line from the console      String lineFromInput = in.readLine();      //create an print writer for writing to a file      PrintWriter out = new PrintWriter(new FileWriter("output.txt"));      //output to the file a line      out.println(lineFromInput);      //close the file (VERY IMPORTANT!)      out.close();   }      catch(IOException e1) {        System.out.println("Error during reading/writing");   }
查看完整描述

3 回答

?
梦里花落0921

TA贡献1772条经验 获得超5个赞

无需编写任何代码,只需在控制台上的cmd中编写即可:


javac myFile.java

java ClassName > a.txt

输出数据存储在a.txt文件中。


查看完整回答
反对 回复 2019-09-20
?
绝地无双

TA贡献1946条经验 获得超4个赞

要保留控制台输出,即写入文件并将其显示在控制台上,您可以使用如下类:


    public class TeePrintStream extends PrintStream {

        private final PrintStream second;


        public TeePrintStream(OutputStream main, PrintStream second) {

            super(main);

            this.second = second;

        }


        /**

         * Closes the main stream. 

         * The second stream is just flushed but <b>not</b> closed.

         * @see java.io.PrintStream#close()

         */

        @Override

        public void close() {

            // just for documentation

            super.close();

        }


        @Override

        public void flush() {

            super.flush();

            second.flush();

        }


        @Override

        public void write(byte[] buf, int off, int len) {

            super.write(buf, off, len);

            second.write(buf, off, len);

        }


        @Override

        public void write(int b) {

            super.write(b);

            second.write(b);

        }


        @Override

        public void write(byte[] b) throws IOException {

            super.write(b);

            second.write(b);

        }

    }

并用于:


    FileOutputStream file = new FileOutputStream("test.txt");

    TeePrintStream tee = new TeePrintStream(file, System.out);

    System.setOut(tee);

(只是一个想法,不完整)


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 1577 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信