首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将控制台输出写入txt文件

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

Stack Overflow用户
提问于 2010-01-03 15:48:26
回答 6查看 400.2K关注 0票数 67

我尝试使用下面的代码建议(http://www.daniweb.com/forums/thread23883.html#)将控制台输出写入txt文件,但是没有成功。怎么了?

代码语言:javascript
复制
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");
   }
EN

回答 6

Stack Overflow用户

发布于 2013-05-09 16:16:14

不需要编写任何代码,只需在控制台的cmd中编写:

代码语言:javascript
复制
javac myFile.java
java ClassName > a.txt

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

票数 36
EN

Stack Overflow用户

发布于 2010-01-03 16:04:11

创建以下方法:

代码语言:javascript
复制
public class Logger {
    public static void log(String message) { 
      PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
      out.write(message);
      out.close();
    }
}

(我没有在上面的类中包含正确的IO处理,而且它不会编译--自己做吧。还要考虑配置文件名。请注意"true“参数。这意味着不会在每次调用该方法时重新创建该文件)

然后调用Logger.log(str)而不是System.out.println(str)

这种手动方法并不可取。使用日志记录框架- slf4j、log4jcommons-logging

票数 12
EN

Stack Overflow用户

发布于 2010-01-03 23:33:15

除了讨论的几种编程方法之外,另一种选择是重定向shell的标准输出。下面是几个UnixDOS示例。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1994255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档