java写文件时,输出不完整的原因以及解决方法close()或flush() 您所在的位置:网站首页 cad打印pdf文件名字符不完整怎么解决 java写文件时,输出不完整的原因以及解决方法close()或flush()

java写文件时,输出不完整的原因以及解决方法close()或flush()

2024-07-11 02:28| 来源: 网络整理| 查看: 265

在java的IO体系中,写文件通常会用到下面语句

BufferedWriter bw=new BufferedWriter(new FileWriter("sql语句.txt"));

用到这个的时候一定不能忘了他的伴侣代码。。

bw.close();

或者

bw.flush();

实际上,FileWriter在写文件时,会把内容存储到一块缓冲区中,当缓冲区满后,才会把缓冲区中的内容写入文件,内容再继续存到缓冲区,如此反复,而flush()方法里面实际是调用了flushBuffer(),会将内存中的内容强制写到文件中,即使内存没满。这就是为什么最后要调用一次fileWriter.close(),close()方法里面同样调用了flushBuffer(),这样就可以了。否则就会最后有少部分的内容缺失。特别是写小文件的时候,会出现文件空白,没有内容。 这个问题很常见,值得注意。下面是jdk7中flushBuffer()的源码。

/** Checks to make sure that the stream has not been closed */ private void ensureOpen() throws IOException { if (out == null) throw new IOException("Stream closed"); } /** * Flushes the output buffer to the underlying character stream, without * flushing the stream itself. This method is non-private only so that it * may be invoked by PrintStream. */ void flushBuffer() throws IOException { synchronized (lock) { ensureOpen(); if (nextChar == 0) return; out.write(cb, 0, nextChar); nextChar = 0; } }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有