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

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


当前回答

我倾向于尽可能依赖于库来进行这种操作。这使我不太可能意外地忽略一个重要的步骤(如上面狼鹬犯的错误)。上面建议了一些库,但我最喜欢的是GoogleGuava。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
}

其他回答

看看Java文件API

快速示例:

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

使用Java 7:

public static void writeToFile(String text, String targetFilePath) throws IOException
{
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}

如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

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

使用Apache Commons IO api。它很简单

使用API作为

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

Maven依赖项

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