How BufferedWriter works in java

I often output text to files. I wonder: how does it work BufferedWriter?

Does text write to a file when I call writer.write(text)? If he does not write text, do I need to use the flash function to write data?

For instance:

       File file = new File("statistics.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        else
        {
            file.delete();
            file.createNewFile();
        }
        FileWriter fileWritter = new FileWriter(file.getAbsoluteFile(),true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        Iterator<Map.Entry<String,Token>> it = listofTakenPairMap.entrySet().iterator();
        int isim_isim=0;
        int isim_fiil=0;
        int zarf_fiil=0;
        while (it.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry pairs = (Map.Entry)it.next();
            Token token=(Token)pairs.getValue();
            String str=pairs.getKey()+ " = " +token.getCount();
            if(token.getTypeOfPairofToken()==0){//isim-isim
                isim_isim+=token.getCount();
            }
            else if(token.getTypeOfPairofToken()==1){
                isim_fiil+=token.getCount();
            }
            else{ //zarf-fiil
                zarf_fiil+=token.getCount();
            }
            System.out.println(str);
            bufferWritter.write(str);
            bufferWritter.newLine();
            //it.remove(); // avoids a ConcurrentModificationException
        }
        bufferWritter.newLine();
        bufferWritter.write("##############################");
        bufferWritter.newLine();
        bufferWritter.write("$isim_isim sayisi :"+isim_isim+"$");
        bufferWritter.newLine();
        bufferWritter.write("$isim_fiil sayisi :"+isim_fiil+"$");
        bufferWritter.newLine();
        bufferWritter.write("$zarf_fiil sayisi :"+zarf_fiil+"$");
        bufferWritter.newLine();
        bufferWritter.write("##############################");
        bufferWritter.flush();
        bufferWritter.close();

If an error occurs in the while loop, the file will be closed without writing data. If I use a function flushin a while loop, then why should I use BufferedWriter? Please correct me if I am wrong.

+5
source share
3 answers

By definition, a buffered writer buffers data and writes it only when it has enough memory to avoid too many file system calls.

finally, , , , , ( , ).

, , , . finally ( Java 7 trye-with-resources, ).

+11

. , - OutputStream Writer, , - . - .

, - . , . .

, ( flush()) , , .

, , Java, .

: write() ( ). ( Stream, FileOutputStream). flush() close(), , , , Stream. flush() close() .

Exception, , . try { } catch (IOException ex) {} .

+1

. : BufferedWriter ?

jdk

, writer.write()? , flush ?

. , write(String s), : write(str, 0, str.length()); openJDK:

  218     public void write(String s, int off, int len) throws IOException {
  219         synchronized (lock) {
  220             ensureOpen();
  221 
  222             int b = off, t = off + len;
  223             while (b < t) {
  224                 int d = min(nChars - nextChar, t - b);
  225                 s.getChars(b, b + d, cb, nextChar);
  226                 b += d;
  227                 nextChar += d;
  228                 if (nextChar >= nChars)
  229                     flushBuffer();
  230             }
  231         }
  232     }
  233      


  118     /**
  119      * Flushes the output buffer to the underlying character stream, without
  120      * flushing the stream itself.  This method is non-private only so that it
  121      * may be invoked by PrintStream.
  122      */
  123     void flushBuffer() throws IOException {
  124         synchronized (lock) {
  125             ensureOpen();
  126             if (nextChar == 0)
  127                 return;
  128             out.write(cb, 0, nextChar);
  129             nextChar = 0;
  130         }
  131     }    

, . if (nextChar >= nChars), ( private static int defaultCharBufferSize = 8192;, "wrapping". ( java, Java IO - Decorator. write(char[] chars, int i, int i1).)

while , . while, BufferedWriter?

The cost of IO is VERY expensive. If you don’t need to look at the output on the fly (for example, look at the log anytime with the latest updates), you should let the performance increase automatically.

+1
source

All Articles