Java Formatter output

本秂侑毒 提交于 2019-12-24 05:25:07

问题


Is it true that the Formatter only writes out when you close the stream?

Code:

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();
        }

At first I forgot to add the finally block with output.close() and when the method got called it would not write anything. So is it correct that a formatter only actually writes its content when you close the stream?


回答1:


The assumption that resource in this case a file is accessed only when you call close() is not valid.

By calling close() you assure that write is done and the resource is released.

The write to it is depend on class BufferedWriter this mean that when you exceed the buffer size the data will be moved from it [buffer] to resource [file]. You can force you app to do that by calling flush(), and that is what close() does.

The default size if buffer is 1KB (8192 bits) long.




回答2:


close() implicitly calls flush(), but you can use flush() whenever you need to send data at that moment.




回答3:


From the documentation: The file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

Classes whose output is buffered will write their stuff when flush is called. This happens implicitely in the close method.

You either have to close it or call flush().




回答4:


you can also use flush() to write data into stream immediately




回答5:


The Formatter outputs at the underlying buffered stream's discretion, but you can force it to do so by calling flush() or close().



来源:https://stackoverflow.com/questions/22042609/java-formatter-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!