« Return to Thread: Empty file without close call with PrintWriter

Empty file without close call with PrintWriter

by Jay Pedersen :: Rate this Message:

Reply to Author | View in Thread

Hi,

I ran into another issue, while writing files from a loop using a PrintWriter ...
I was getting empty files (for the smaller files) if I didn't add a close() call.

This is Groovy 1.6.3 with Java 1.6.0_13 on 64-bit windows machine,
compiling with groovyc and executing with java -Xint

So .. it seems like the program exited, and the PrinterWriters
didn't ever write their output.

Code:  (which has the close call -- remove to get the empty files, files 3 to 5 on my system were empty):


def binstr = { v, n=4 ->
  def s = ("0"*n + Integer.toBinaryString(v))
  return s.substring(s.size()-n)
}

def uniqcols = { a, b, cols=4 ->
    def l = [] as HashSet
    0.upto(cols-1) { bitno ->
      def bitmask = 1<<bitno
      switch (bitno) {
        case 0  : valu = ((a&bitmask) << 1)         | (b&bitmask)
                  break
        default : valu = ((a&bitmask) >> (bitno-1)) | ((b&bitmask) >> bitno)
                  break
       }
      l << valu  // add value to set
    }
    // println l
    return l.size()
}

3.upto(8) { n ->
 def lastval = 2**n - 1
 def spacefill = " "*(n+1)
 def fmtstr = "%${n}d "
 println "${fmtstr}"

 def File file = new File("k2m${n}.txt")
 def PrintWriter writer = file.newPrintWriter()

 // heading
 writer.print spacefill
 0.upto(lastval) { i -> writer.print "${binstr(i,n)} " };
 writer.println ""

 // data lines
 0.upto(lastval) { i -> 
  writer.print "${binstr(i,n)} "
  0.upto(lastval) { j ->
    writer.print String.format(fmtstr, n-uniqcols(i,j,n))
  }
  writer.println ""
 }
 writer.close()  // files 3 to 5 empty without this!
}

 « Return to Thread: Empty file without close call with PrintWriter