If you're simply outputting text, rather than any binary data, the following will work:
(如果您只是输出文本,而不是任何二进制数据,则可以执行以下操作:)
PrintWriter out = new PrintWriter("filename.txt");
Then, write your String to it, just like you would to any output stream:
(然后,将String写入其中,就像写入任何输出流一样:)
out.println(text);
You'll need exception handling, as ever.
(与以往一样,您将需要异常处理。)
Be sure to call out.close()
when you've finished writing. (完成编写后,请确保调用out.close()
。)
If you are using Java 7 or later, you can use the " try-with-resources statement " which will automatically close your PrintStream
when you are done with it (ie exit the block) like so:
(如果您使用的是Java 7或更高版本,则可以使用“ try-with-resources语句 ”,当使用完它(即退出该块)后,它将自动关闭PrintStream
,如下所示:)
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
You will still need to explicitly throw the java.io.FileNotFoundException
as before.
(您仍然需要像以前一样显式抛出java.io.FileNotFoundException
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…