我尝试使用下面的代码建议(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");
}
发布于 2013-05-09 16:16:14
不需要编写任何代码,只需在控制台的cmd中编写:
javac myFile.java
java ClassName > a.txt
输出数据存储在a.txt文件中。
发布于 2010-01-03 16:04:11
创建以下方法:
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、log4j、commons-logging等
https://stackoverflow.com/questions/1994255
复制相似问题