Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-7465

ResourceGroovyMethods/NioGroovyMethods BOM behavior is inconsistent

    XMLWordPrintableJSON

Details

    Description

      Most users would expect withPrintWriter to be a convenience method that behaves the same as if they had called new PrintWriter themselves, but this is not the current behavior:

      File file = new File("tmp.txt")
      try {
          String text = " "
          String charset = "UTF-16LE"
      
          file.withPrintWriter(charset) { it << text }
          println "withPrintWriter"
          file.getBytes().each { System.out.format("%02x ", it) }
      
          PrintWriter w = new PrintWriter(file, charset)
          w.print(text)
          w.close()
          println "\n\nnew PrintWriter"
          file.getBytes().each { System.out.format("%02x ", it) }
      } finally {
          file.delete()
      }
      

      Outputs

      withPrintWriter
      ff fe 20 00 
      
      new PrintWriter
      20 00
      

      Additionally most users would expect that there's no difference in behavior between NIO and traditional methods, but this is also not the case

      import java.nio.file.Files
      import java.nio.file.FileSystems
      import java.nio.file.Path
      
      File file = new File("tmp1.txt")
      Path path = FileSystems.getDefault().getPath("tmp2.txt")
      try {
          String text = " "
          String charset = "UTF-16LE"
      
          file.withPrintWriter(charset) { it << text }
          println "withPrintWriter"
          file.getBytes().each { System.out.format("%02x ", it) }
      
          path.withPrintWriter(charset) { it << text }
          println "\n\nnio withPrintWriter"
          path.getBytes().each { System.out.format("%02x ", it) }
      } finally {
          file.delete()
          Files.delete(path)
      }
      

      outputs

      withPrintWriter
      ff fe 20 00
      
      nio withPrintWriter
      20 00
      

      This is because ResourceGroovyMethods have a writeUTF16BomIfRequired method that NioGroovyMethods don't.

      Most likely we'd want to change ResourceGroovyMethods to not add the BOM by default, or at least allow the user to opt out of that behavior by doing something like adding a boolean argument to the existing methods that would control that behavior. The other option would be to make the NIO methods consistent by having them also use writeUTF16BomIfRequired.

      This began as a discussion on the user mailing list.

      Attachments

        Issue Links

          Activity

            People

              keegan Keegan Witt
              keegan Keegan Witt
              Votes:
              0 Vote for this issue
              Watchers:
              3 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: