Java 如何将控制台输出写入txt文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1994255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write console output to a txt file
提问by Jessy
I have tried to write the console output to a txt file using this code suggestion (http://www.daniweb.com/forums/thread23883.html#) however I was not successful. What's wrong?
我曾尝试使用此代码建议 ( 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");
}
采纳答案by Stephen C
You need to do something like this:
你需要做这样的事情:
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
The second statement is the key. It changes the value of the supposedly "final" System.out
attribute to be the supplied PrintStream value.
第二个说法是关键。它将所谓的“最终”System.out
属性的值更改为提供的 PrintStream 值。
There are analogous methods (setIn
and setErr
) for changing the standard input and error streams; refer to the java.lang.System
javadocs for details.
有类似的方法(setIn
和setErr
)来改变标准输入和错误流;java.lang.System
有关详细信息,请参阅javadoc。
A more general version of the above is this:
上面更通用的版本是这样的:
PrintStream out = new PrintStream(
new FileOutputStream("output.txt", append), autoFlush);
System.setOut(out);
If append
is true
, the stream will append to an existing file instead of truncating it. If autoflush
is true
, the output buffer will be flushed whenever a byte array is written, one of the println
methods is called, or a \n
is written.
如果append
是true
,则流将附加到现有文件而不是截断它。如果autoflush
是true
,则每当写入字节数组、println
调用其中一种方法或写入 a 时,都会刷新输出缓冲区\n
。
I'd just like to add that it is usually a better idea to use a logging subsystem like Log4j, Logbackor the standard Java java.util.loggingsubsystem. These offer fine-grained logging control via runtime configuration files, support for rolling log files, feeds to system logging, and so on.
我只想补充一点,使用Log4j、Logback或标准 Java java.util.logging子系统等日志子系统通常是一个更好的主意。这些通过运行时配置文件提供细粒度的日志控制、对滚动日志文件的支持、系统日志的馈送等。
Alternatively, if you are not "logging" then consider the following:
或者,如果您不是“日志记录”,请考虑以下事项:
With typical shells, you can redirecting standard output (or standard error) to a file on the command line; e.g.
$ java MyApp > output.txt
For more information, refer to a shell tutorial or manual entry.
You could change your application to use an
out
stream passed as a method parameter or via a singleton or dependency injection rather than writing toSystem.out
.
使用典型的 shell,您可以将标准输出(或标准错误)重定向到命令行上的文件;例如
$ java MyApp > output.txt
有关更多信息,请参阅 shell 教程或手册条目。
您可以更改您的应用程序以使用
out
作为方法参数传递的流或通过单例或依赖项注入而不是写入System.out
.
Changing System.out
may cause nasty surprises for other code in your JVM that is not expecting this to happen. (A properly designed Java library will avoid depending on System.out
and System.err
, but you could be unlucky.)
更改System.out
可能会导致您的 JVM 中的其他代码意外发生,而这些代码并没有预料到会发生这种情况。(设计合理的 Java 库将避免依赖System.out
和System.err
,但您可能会很不走运。)
回答by ZoogieZork
You can use System.setOut()at the start of your program to redirect all output via System.out
to your own PrintStream
.
您可以在程序开始时使用System.setOut()将所有输出重定向System.out
到您自己的PrintStream
.
回答by Bozho
Create the following method:
创建以下方法:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
(我没有在上面的类中包含正确的 IO 处理,它不会编译 - 自己做。还要考虑配置文件名。注意“true”参数。这意味着不会重新创建文件每次调用该方法时)
Then instead of System.out.println(str)
call Logger.log(str)
然后而不是System.out.println(str)
打电话Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
这种手动方法并不可取。使用日志框架 - slf4j、log4j、commons-logging等等
回答by user85421
to preservethe console output, that is, write to a file and also have it displayed on the console, you could use a class like:
要保留控制台输出,即写入文件并将其显示在控制台上,您可以使用如下类:
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);
}
}
and used as in:
并用于:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)
(只是一个想法,不完整)
回答by trashgod
回答by Abhiyank
This is my idea of what you are trying to do and it works fine:
这是我对您要尝试执行的操作的想法,并且效果很好:
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter("c://output.txt"));
try {
String inputLine = null;
do {
inputLine=in.readLine();
out.write(inputLine);
out.newLine();
} while (!inputLine.equalsIgnoreCase("eof"));
System.out.print("Write Successful");
} catch(IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
回答by ali ahmad
There is no need to write any code, just in cmd on the console you can write:
无需编写任何代码,只需在控制台的cmd中即可编写:
javac myFile.java
java ClassName > a.txt
The output data is stored in the a.txt file.
输出数据存储在 a.txt 文件中。
回答by Prakash Kandel
The easiest way to write console output to text file is
将控制台输出写入文本文件的最简单方法是
//create a file first
PrintWriter outputfile = new PrintWriter(filename);
//replace your System.out.print("your output");
outputfile.print("your output");
outputfile.close();
回答by Ashish Vishnoi
To write console output to a txt file
将控制台输出写入 txt 文件
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A TEXT FILE";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
FileWriter writer = null;
try {
writer = new FileWriter("final.txt");
writer.write(listString);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to generate the PDF rather then the text file, you use the dependency given below:
如果要生成 PDF 而不是文本文件,请使用下面给出的依赖项:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>
To generate a PDF, use this code:
要生成 PDF,请使用以下代码:
public static void main(String[] args) {
int i;
List<String> ls = new ArrayList<String>();
for (i = 1; i <= 100; i++) {
String str = null;
str = +i + ":- HOW TO WRITE A CONSOLE OUTPUT IN A PDF";
ls.add(str);
}
String listString = "";
for (String s : ls) {
listString += s + "\n";
}
Document document = new Document();
try {
PdfWriter writer1 = PdfWriter
.getInstance(
document,
new FileOutputStream(
"final_pdf.pdf"));
document.open();
document.add(new Paragraph(listString));
document.close();
writer1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
回答by dhayanand baskar
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("C:\testing.txt"));
} catch (IOException e) {
e.printStackTrace();
}
out.println("output");
out.close();
I am using absolute path for the FileWriter. It is working for me like a charm. Also Make sure the file is present in the location. Else It will throw a FileNotFoundException. This method does not create a new file in the target location if the file is not found.
我正在为 FileWriter 使用绝对路径。它对我来说就像一种魅力。还要确保该文件存在于该位置。否则它会抛出一个 FileNotFoundException。如果找不到文件,此方法不会在目标位置创建新文件。