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

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


当前回答

使用org.apache.mons.io.FileUtils:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());

其他回答

使用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>

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

如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

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

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

我已经发布了一个库,它保存文件,并且只使用一行代码处理所有内容,您可以在这里找到它及其文档

Github存储库

你的问题答案很简单

String path = FileSaver
        .get()
        .save(string.getBytes(),"file.txt");