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

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

其他回答

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

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

使用Apache Commons IO api。它很简单

使用API作为

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

Maven依赖项

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

在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

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

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
        }
    }
}

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

private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}