格式化程序只在关闭流时才会写出来吗?
码:
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();
}
Run Code Online (Sandbox Code Playgroud)
起初我忘了用output.close()添加finally块,当调用该方法时,它不会写任何东西.那么格式化程序在关闭流时只实际写入其内容是否正确?
假设在这种情况下资源仅在您调用时访问该文件close() 无效.
通过调用close()您可以确保写入已完成并且资源已释放.
对它的写入取决于类,BufferedWriter这意味着当你超过缓冲区大小时,数据将从它[缓冲区]移动到资源[文件].您可以通过调用强制您应用程序执行此操作flush(),这就是做什么close().
缓冲区长度为1KB(8192位)时的默认大小.