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

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

问题描述

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



如何将text变量的内容保存到如果你只是输出文本,而不是任何二进制数据,下面的工作:

>

  PrintWriter out = new PrintWriter(filename.txt); 

然后,写下你的字符串,就像你对任何输出流一样:

  out.println(text); 

您将需要异常处理。请确保在完成写作时调用 out.close()如果您正在使用Java 7或更高版本,您可以使用试用资源声明,它会自动关闭你的 PrintStream 当你完成它(即退出块),如下所示:



<$ (printWriter out = new PrintWriter(filename.txt)){
out.println(text); pre>



$ b

你仍然需要显式地抛出 java。 io.FileNotFoundException 和以前一样。


In Java, I have text from a text field in a String variable called "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);

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

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 );
}

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

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

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