如何使用 Java 将字符串保存到文本文件?
在 Java 中,我有来自名为“text”的字符串变量中的文本字段的文本。
如何将“text”变量的内容保存到文件中?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(24)
如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:
然后,将字符串写入其中,就像写入任何输出流一样:
您将一如既往地需要异常处理。 完成写入后请务必关闭输出流。
如果您使用的是 Java 7 或更高版本,则可以使用“try-with -resources 语句”,当您完成它(即退出块)时,它将自动关闭您的
PrintStream
,如下所示:您仍然需要显式抛出
java.io .FileNotFoundException 和以前一样。
If you're simply outputting text, rather than any binary data, the following will work:
Then, write your String to it, just like you would to any output stream:
You'll need exception handling, as ever. Be sure to close the output stream 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:You will still need to explicitly throw the
java.io.FileNotFoundException
as before.Apache Commons IO 包含一些很棒的方法来执行此操作,特别是 FileUtils 包含以下方法:
它允许您在一个方法调用中将文本写入文件:
您可能还需要考虑指定文件的编码。
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
which allows you to write text to a file in one method call:
You might also want to consider specifying the encoding for the file as well.
在 Java 7 中你可以这样做:
这里有更多信息:
http://www.drdobbs.com/jvm/java -se-7-new-file-io/231600403
In Java 7 you can do this:
There is more info here:
http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
查看 Java 文件 API
一个简单的例子:
Take a look at the Java File API
a quick example:
刚刚在我的项目中做了类似的事情。 使用 FileWriter 将简化您的部分工作。 在这里您可以找到不错的教程。
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
使用 Apache Commons IO 中的
FileUtils.writeStringToFile()
。 无需重新发明这个特定的轮子。Use
FileUtils.writeStringToFile()
from Apache Commons IO. No need to reinvent this particular wheel.在 Java 11 中,java.nio.file.Files 类通过两个新的实用方法进行了扩展,用于将字符串写入文件。 第一种方法(参见JavaDoc 此处) 使用字符集 UTF-8 默认:
第二种方法(参见 JavaDoc 此处) 允许指定个人字符集:
两种方法都有一个可选的 Varargs 参数,用于设置文件处理选项(请参阅 JavaDoc 此处)。 以下示例将创建一个不存在的文件或将字符串附加到现有文件中:
In Java 11 the
java.nio.file.Files
class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:And the second method (see JavaDoc here) allows to specify an individual charset:
Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:
您可以使用修改下面的代码来从处理文本的任何类或函数写入文件。 人们想知道为什么世界需要一个新的文本编辑器......
You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...
我更喜欢尽可能依赖库来进行此类操作。 这使得我不太可能意外地遗漏重要的步骤(就像上面狼鹬犯的错误一样)。 上面推荐了一些库,但我最喜欢的就是 Google Guava。 Guava 有一个名为 Files 非常适合此任务:
I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:
如果您需要基于一个字符串创建文本文件:
In case if you need create text file based on one single string:
使用Java 7:
Using
Java 7
:使用 Apache Commons IO API。 其简单
使用 API 作为
Maven 依赖项
Use Apache Commons IO api. Its simple
Use API as
Maven Dependency
使用这个,它非常可读:
Use this, it is very readable:
您可以将此方法插入到您的类中。 如果您在具有 main 方法的类中使用此方法,请通过添加 static 关键字将该类更改为静态。 无论哪种方式,您都需要导入 java.io.* 才能使其工作,否则 File、FileWriter 和 BufferedWriter 将无法被识别。
You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.
你可以这样做:
You could do this:
使用 org.apache.commons.io.FileUtils:
Using org.apache.commons.io.FileUtils:
如果您只关心将一个文本块推送到文件,则每次都会覆盖它。
此示例允许用户使用文件选择器选择文件。
If you only care about pushing one block of text to file, this will overwrite it each time.
This example allows the user to select a file using a file chooser.
基本上与这里的答案相同,但易于复制/粘贴,而且它可以正常工作;-)
Basically the same answer as here, but easy to copy/paste, and it just works ;-)
最好在finally块中关闭编写器/输出流,以防万一发生什么情况
It's better to close the writer/outputstream in a finally block, just in case something happen
我认为最好的方法是使用
Files.write(Path path, Iterablelines, OpenOption... options)
:参见 javadoc:
请注意。 我看到人们已经用 Java 的内置
Files.write
进行了回答,但是我的回答中的特别之处似乎没有人提到的是该方法的重载版本,该方法采用 CharSequence 的 Iterable(即字符串) ,而不是byte[]
数组,因此不需要text.getBytes()
,我认为这更干净一些。I think the best way is using
Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options)
:See javadoc:
Please note. I see people have already answered with Java's built-in
Files.write
, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of abyte[]
array, thustext.getBytes()
is not required, which is a bit cleaner I think.如果您希望将字符串中的回车符保留到文件中
这是一个代码示例:
If you wish to keep the carriage return characters from the string into a file
here is an code example:
我发布了一个保存文件的库,只需一行代码即可处理所有内容,您可以在这里找到它及其文档
Github 存储库
你的问题的答案很简单
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
由于在所有Android版本上运行并且需要影响URL/URI等资源,因此我的方式是基于流的,欢迎任何建议。
就流(InputStream 和 OutputStream)而言,传输的是二进制数据,当开发人员要向流中写入字符串时,必须首先将其转换为字节,或者换句话说,对其进行编码。
My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.
As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.