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

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


当前回答

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

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

其他回答

看看Java文件API

快速示例:

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

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

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:

public static void writeToFile(String text, String targetFilePath) throws IOException
{
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}

使用这个,它非常易读:

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);

我认为最好的方法是使用File.write(路径路径,Iterable<?extends CharSequence>行,OpenOption…options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

参见javadoc:

将文本行写入文件。每一行都是一个字符序列按顺序写入文件,每行以平台的行分隔符,由系统属性定义line.separator。字符使用指定的字符集。options参数指定如何创建或打开文件。如果不存在任何选项,则该方法的工作方式与CREATE,存在TRUNCATE_EXISTING和WRITE选项。换句话说打开文件进行写入,如果文件不存在则创建文件,或最初将现有的常规文件截断为0的大小。这个方法确保文件在所有行都已关闭时关闭写入(或引发I/O错误或其他运行时异常)。如果如果发生I/O错误,则可能会在文件创建或或者在一些字节被写入文件之后。

请注意。我看到人们已经用Java内置的Files.write进行了回答,但我的回答中有一个特别之处,似乎没有人提到,那就是重载版本的方法,它采用了CharSequence的Iterable(即String),而不是byte[]数组,因此不需要text.getBytes(),我认为这有点干净。