如何使用 Java 将字符串保存到文本文件? [英] How do I save a String to a text file using Java?

查看:30
本文介绍了如何使用 Java 将字符串保存到文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我从名为text"的字符串变量中的文本字段获取文本.

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

如何将text"变量的内容保存到文件中?

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

推荐答案

如果您只是输出文本,而不是任何二进制数据,以下方法将起作用:

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:

out.println(text);

您将一如既往地需要异常处理.写完后一定要调用out.close().

You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing.

如果您使用的是 Java 7 或更高版本,则可以使用try-with-resources 语句",它会在您完成后自动关闭您的 PrintStream(即退出块),如下所示:

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:

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

您仍然需要像以前一样显式抛出 java.io.FileNotFoundException.

You will still need to explicitly throw the java.io.FileNotFoundException as before.

这篇关于如何使用 Java 将字符串保存到文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆