在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
当前回答
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);
}
}
其他回答
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
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);
}
});
使用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>
基本上与这里的答案相同,但易于复制/粘贴,而且效果很好;-)
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);
}
}
你可以这样做:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
我认为最好的方法是使用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(),我认为这有点干净。