在Java中,我有一个名为“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)
    {
    }
}

其他回答

基本上与这里的答案相同,但易于复制/粘贴,而且效果很好;-)

  import java.io.FileWriter;

  public void saveToFile(String data, String filename) {
    try (
      FileWriter fw = new FileWriter(filename)) {
      fw.write(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

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

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

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

如果您只关心将一个文本块推送到文件中,那么每次都会覆盖它。

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

此示例允许用户使用文件选择器选择文件。

在Java 7中,您可以执行以下操作:

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

这里有更多信息:http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403