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

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


当前回答

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

static void writeStringToFile(File file, String data, Charset charset) 

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

FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));

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

其他回答

你可以这样做:

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

看看Java文件API

快速示例:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}
private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}

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

使用Apache Commons IO中的FileUtils.writeStringToFile()。无需重新发明这个轮子。