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

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


当前回答

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

其他回答

最好在finally块中关闭writer/outputstream,以防发生意外

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}

您可以使用下面的修改代码从处理文本的任何类或函数编写文件。有人想知道为什么世界需要一个新的文本编辑器。。。

import java.io.*;

public class Main {

    public static void main(String[] args) {

        try {
            String str = "SomeMoreTextIsHere";
            File newTextFile = new File("C:/thetextfile.txt");

            FileWriter fw = new FileWriter(newTextFile);
            fw.write(str);
            fw.close();

        } catch (IOException iox) {
            //do stuff with exception
            iox.printStackTrace();
        }
    }
}

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

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

如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:

PrintWriter out = new PrintWriter("filename.txt");

然后,将String写入其中,就像写入任何输出流一样:

out.println(text);

您将一如既往地需要异常处理。写完后一定要调用.close()。

如果您使用的是Java 7或更高版本,则可以使用“try with resources语句”,该语句将在完成PrintStream(即退出块)后自动关闭PrintStream,如下所示:

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

您仍然需要像以前一样显式抛出java.io.FileNotFoundException。

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