如何使用 Java 将字符串保存到文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1053467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:50:08  来源:igfitidea点击:

How do I save a String to a text file using Java?

javafilefile-iotext-files

提问by Justin White

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

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

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

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

回答by Jorn

Take a look at the Java File API

看一看Java 文件 API

a quick example:

一个简单的例子:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}

回答by skaffman

Use FileUtils.writeStringToFile()from Apache Commons IO. No need to reinvent this particular wheel.

使用FileUtils.writeStringToFile()来自Apache的百科全书IO。无需重新发明这个特定的轮子。

回答by Artem Barger

Just did something similar in my project. Use FileWriterwill simplify part of your job. And here you can find nice tutorial.

刚刚在我的项目中做了类似的事情。使用FileWriter将简化您的部分工作。在这里你可以找到很好的教程

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}

回答by Jeremy Smyth

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.

您将一如既往地需要异常处理。out.close()写完后一定要打电话。

If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStreamwhen 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.FileNotFoundExceptionas before.

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

回答by Jon

Apache Commons IOcontains some great methods for doing this, in particular FileUtils contains the following method:

Apache Commons IO包含一些很好的方法,特别是 FileUtils 包含以下方法:

static void writeStringToFile(File file, String data) 

which allows you to write text to a file in one method call:

它允许您在一个方法调用中将文本写入文件:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

You might also want to consider specifying the encoding for the file as well.

您可能还需要考虑为文件指定编码。

回答by Jon

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...

您可以使用修改下面的代码从处理文本的任何类或函数写入文件。有人想知道为什么世界需要一个新的文本编辑器......

import java.io.*;

public class Main {

    public static void main(String[] args) {

        try {
            String str = "SomeMoreTextIsHere";
            File newTextFile = new File("C:/thetextfile.txt");

            FileWriter fw = new FileWriter(newTextFile);
            fw.write(str);
            fw.close();

        } catch (IOException iox) {
            //do stuff with exception
            iox.printStackTrace();
        }
    }
}

回答by Jon

It's better to close the writer/outputstream in a finally block, just in case something happen

最好在 finally 块中关闭编写器/输出流,以防万一

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}

回答by Mostafa Rezaei

You could do this:

你可以这样做:

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

回答by Spina

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 Fileswhich works nicely for this task:

对于此类操作,我更喜欢尽可能依赖库。这让我不太可能不小心遗漏了一个重要的步骤(比如上面犯的错误 wolfsnipes)。上面建议了一些库,但我最喜欢这种东西的是Google Guava。Guava 有一个名为Files的类,它非常适合此任务:

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}

回答by Anirban Chakrabarti

Use Apache Commons IO api. Its simple

使用 Apache Commons IO api。这很简单

Use API as

使用 API 作为

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven Dependency

Maven 依赖

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>