在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。

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


当前回答

我已经发布了一个库,它保存文件,并且只使用一行代码处理所有内容,您可以在这里找到它及其文档

Github存储库

你的问题答案很简单

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");

其他回答

看看Java文件API

快速示例:

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

只是在我的项目中做了类似的事情。使用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)
    {
    }
}

在Java 7中,您可以执行以下操作:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

这里有更多信息:http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

在Java11中,Java.nio.file.Files类被两个新的实用程序方法扩展,以将字符串写入文件。第一种方法(请参阅此处的JavaDoc)使用UTF-8字符集作为默认值:

Files.writeString(Path.of("my", "path"), "My String");

第二种方法(参见此处的JavaDoc)允许指定单个字符集:

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

这两种方法都有一个可选的Varargs参数,用于设置文件处理选项(请参阅此处的JavaDoc)。以下示例将创建一个不存在的文件或将字符串附加到现有文件:

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

如果您只关心将一个文本块推送到文件中,那么每次都会覆盖它。

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

此示例允许用户使用文件选择器选择文件。