0

Is there a way to write a com.squareup.javapoet.JavaFile to the file system and make sure the file always is encoded using UTF-8?

Currently I am using com.squareup.javapoet.JavaFile#writeTo(java.io.File dir) but this uses the default encoding of the current virtual machine.

saw303
  • 8,051
  • 7
  • 50
  • 90

1 Answers1

1

Looking at the Github-Page of Javapoet, you can use the Method:

JavaFile.writeTo(PrintStream)

So you should be able to create a PrintStream using UTF-8 und write the file like this:

PrintStream stream = new PrintStream("YourTargetFile.java", "UTF-8");
yourJavaFileObject.writeTo(stream);
Felix
  • 2,256
  • 2
  • 15
  • 35
  • I was looking at the https://github.com/square/javapoet/blob/master/README.md but was not able to find a documentation about it. Thanks a lot. This works perfect. Nevertheless it has the downside, that you have to name Java file and create all it package directories yourself. – saw303 Jun 08 '17 at 08:28
  • It wasn't really that clear from the README, but I saw that JavaFile.writeTo(System.out) was used and since that's an PrintStream I knew that this will work. Another possible way would be the use JavaFile.toString() and write the resulting String into a File manually. – Felix Jun 08 '17 at 08:38
  • 1
    I will file an issue to introduce a new `writeTo(File directory, Charset encoding)` method for convenience. – saw303 Jun 08 '17 at 08:50