0

I am trying to encode an image file to a Base64 String using the directions on this site. The only difference is I have a groovy script (instead of Java), my entire script is just....

  @Grapes(
    @Grab(group='commons-io', module='commons-io', version='2.6')
  )

 import org.apache.commons.io.FileUtils
 import org.apache.commons.codec.binary.Base64


  byte[] fileContent = FileUtils.readFileToByteArray(new File('/Users/me/Test.jpeg'));
  String encodedString = Base64.getEncoder().encodeToString(fileContent);

When I run this I get the below exception and can't figure out why...

 groovy.lang.MissingMethodException: 
 No signature of method: static org.apache.commons.codec.binary.Base64.getEncoder() is applicable for argument types: () values: []
 Possible solutions: encode([B), encode(java.lang.Object)
AbuMariam
  • 3,282
  • 13
  • 49
  • 82
  • 2
    The Base64 class doesn't have a getEncoder() method, but it does have a bunch of methods to encode: https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html – SourMonk May 10 '19 at 13:20
  • 4
    in groovy it's possible to do the same without external libraries: `new File('/Users/me/Test.jpeg').getBytes().encodeBase64()` – daggett May 10 '19 at 13:43

1 Answers1

0

You're importing org.apache.commons.codec.binary.Base64.

With Base64.getEncoder().encodeToString(fileContent) you're calling java.util.Base64, which has methods other than org.apache.commons.codec.binary.Base64.

Since java.util.* is one of Groovy's default imports your code should work when you remove import org.apache.commons.codec.binary.Base64.

aventurin
  • 2,056
  • 4
  • 26
  • 30