在Java中,我有一个名为“text”的字符串变量中的文本字段中的文本。
如何将“文本”变量的内容保存到文件中?
在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.writeStringToFile()。无需重新发明这个轮子。
看看Java文件API
快速示例:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
我已经发布了一个库,它保存文件,并且只使用一行代码处理所有内容,您可以在这里找到它及其文档
Github存储库
你的问题答案很简单
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");
如果您只是输出文本,而不是任何二进制数据,则以下操作将起作用:
PrintWriter out = new PrintWriter("filename.txt");
然后,将String写入其中,就像写入任何输出流一样:
out.println(text);
您将一如既往地需要异常处理。写完后一定要调用.close()。
如果您使用的是Java 7或更高版本,则可以使用“try with resources语句”,该语句将在完成PrintStream(即退出块)后自动关闭PrintStream,如下所示:
try (PrintWriter out = new PrintWriter("filename.txt")) {
out.println(text);
}
您仍然需要像以前一样显式抛出java.io.FileNotFoundException。
如果希望将字符串中的回车字符保留在文件中下面是一个代码示例:
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);
}
});