格式化程序只在您关闭流时才会写出来吗?
代码:
public void save(String content, String filename) {
if(filename!=""){
setFileName(filename);
try {
output = new Formatter(new File(fileName));
output.format("%s",content);
} catch (FormatterClosedException ex){
System.err.println("Error writing to file");
return;
} catch ( NoSuchElementException ex){
System.err.println("invalid input");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
output.close();
}
起初我忘了用output.close()添加finally块,当调用该方法时,它不会写任何东西。那么格式化程序在关闭流时只实际写入其内容是否正确?
答案 0 :(得分:5)
假设仅在您致电close()
时访问此文件中的资源无效。
通过调用close()
,您可以确保完成写入并释放资源。
对它的写入取决于类BufferedWriter
这意味着当你超过缓冲区大小时,数据将从它[缓冲区]移动到资源[文件]。您可以通过调用flush()
强制您启动应用,这就是close()
所做的事情。
如果缓冲区长度为1KB(8192位),则为默认大小。
答案 1 :(得分:1)
来自documentation: 用作此格式化程序的目标的文件。如果该文件存在,那么它将被截断为零大小;否则,将创建一个新文件。输出将被写入文件并被缓冲。
缓冲输出的类将在调用flush
时写入其内容。这在close
方法中隐含地发生。
您必须关闭它或致电flush()
。
答案 2 :(得分:1)
close()隐式调用flush(),但是每当需要发送数据时都可以使用flush()。
答案 3 :(得分:0)
您也可以使用flush()
立即将数据写入流
答案 4 :(得分:0)
基础缓冲流的Formatter
输出可自行决定,但您可以通过调用flush()
或close()
强制执行此操作。