在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在Java中,我有一个名为“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"));
您可能还需要考虑指定文件的编码。
其他回答
我倾向于尽可能依赖于库来进行这种操作。这使我不太可能意外地忽略一个重要的步骤(如上面狼鹬犯的错误)。上面建议了一些库,但我最喜欢的是GoogleGuava。Guava有一个名为Files的类,非常适合此任务:
// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
// Useful error handling here
}
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);
}
}
基本上与这里的答案相同,但易于复制/粘贴,而且效果很好;-)
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);
}
}
我认为最好的方法是使用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(),我认为这有点干净。
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
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);
}
});