Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - 如何使用Java将字符串保存到文本文件?(How do I save a String to a text file using Java?)

In Java, I have text from a text field in a String variable called "text".

(在Java中,我来自一个名为“ text”的String变量中的文本字段中的文本。)

How can I save the contents of the "text" variable to a file?

(如何将“文本”变量的内容保存到文件中?)

  ask by Justin White translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...