如何用Java将一个字符串保存到一个文本文件中?

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

我怎样才能将"text"变量的内容保存到文件中?

看一下Java文件API

一个快速的例子。

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

在我的项目中刚刚做了类似的事情。使用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)
    {
    }
}
评论(6)

使用Apache Commons IOFileUtils.writeStringToFile()。没有必要重新发明这个特殊的轮子。

评论(11)