将所有程序控制台输出记录到按需文件
我有一个实现记录方法的任务,该方法将将所有程序内容带入记录方法调用并将其保存到文件。该方法不应覆盖文件中的信息,而应在文件中添加新内容。
我需要写的内容:
- 所有程序消息和输出;
- 所有用户输入都以在控制台上出现的方式(该程序询问了几次);
我对它的想法是创建一个StringBuilder对象并开始将所有内容附加到它上。调用日志记录方法后,请要求一个文件将log保存到StringBuilder的内容并将其保存到其中。然后冲洗弦乐器并继续收集信息。在第二个调用中,如果提供了相同的文件名,只需附加StringBuilder收集的新信息即可。
但是,这意味着我需要在程序输出和用户输入所在地的整个地方放置聚会调用。对我来说似乎不是最佳的。
关于如何以不同和更优化的方式实现我的目标有什么想法?
先感谢您。
此致, VADIM
更新:我实际上能够重定向系统。Out将所有内容收集到bytearraystream,然后按需写入文件。但是我仍然不明白如何为Inputstream做到这一点。我不需要重定向,我仍然必须从键盘输入evyyrthing,只是值得在正确的位置登录的值。我仍在寻找解决方案。
I have a task to implement a logging method that will take all program content up to logging method call and save it to file. The method should not overwrite already present info in file, but rather add new content to it.
What I need to write:
- all program messages and output;
- all user inputs in the way they appear on console (the program inquires it several times);
My thought on it is to create a StringBuilder object and start appending everything to it. Once logging method is invoked, ask for a file to save log to and save contents of StringBuilder to it. Then flush StringBuilder and continue to gather information. On second invocation, if the same filename is provided, just append new info gathered by StringBuilder.
However, this means that I will need to place gathering invocations all over the place where program output and user input are. Seems like not very optimal to me.
Are there any ideas on how to reach my goal differently and more optimally?
Thank you in advance.
Best regards,
Vadim
UPDATE: I actually was able to redirect system.out to gather everything to ByteArrayStream and then write to file on demand. But I still don't understand how to do it for inputstream. I don't need to redirect it, I still have to input eveyrthing from keyboard, it's just values that have to make it to logs in correct places. Am still searching for a solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要重新发明轮子。去登录框架。有一个集成到java 。
另外,您可以使用 log4j ,还有其他此类框架。
Do not reinvent the wheel. Go for a logging framework. There is one integrated into java anyway.
Alternatively you can use log4j, and there are other such frameworks out there.