Definitely solve problems with strange characters in Java

4

I had a problem and resolved it as follows:

javac -encoding UTF-8 nomedoarquivo.java

How can I make this command set for all files already?

    
asked by anonymous 04.07.2016 / 06:41

1 answer

4

Ideally, you should use a tool to compile your programs.

It may be an IDE such as Eclipse or Netbeans, where you then set the project as UTF-8 and you can still set additional compiler parameters, but it depends on which IDE you use and which version.

Preferably a build tool such as Maven or Gradle helps you define the project independent of the IDE. In Maven, you can simply define the encoding in the configuration of the project that is in the pom.xml file. Example:

<project>
  ...
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  ...
</project>

If you really need to use the command line, you can try setting the environment variable JAVA_TOOL_OPTIONS containing the parameters you want to use in the javac command. The problem with this approach is that you affect the entire environment.

A simpler solution for a small personal project is to create a script (batch for Windows, bash for Linux, or whatever you have available) that runs the build process automatically in your project.

And it's always good to remember that it's not just time to compile classes that you may have problems. Preferably, run the java command also by passing the -Dfile.encoding=UTF-8 encoding parameter through your IDE or command line as you like.

Also remember that it is recommended to pass the encoding whenever you convert bytes to strings and vice versa, whenever you read or write files, transmit data over the network, return data in requests, and so on.

    
04.07.2016 / 09:46