在Java中,我在一个名为"text"的字符串变量中拥有一个文本字段的文本。
我怎样才能将"text"变量的内容保存到文件中?
看一下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)
{
}
}
使用Apache Commons IO的FileUtils.writeStringToFile()
。没有必要重新发明这个特殊的轮子。