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

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


当前回答

看看Java文件API

快速示例:

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

其他回答

最好在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文件API

快速示例:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(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"));

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

在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