#482 Add checks to ban usage of platform default encoding


The following classes/methods use the platform's default encoding and as such are inherently platform-dependent. However, platform-dependence is usually not what Java developers seek. Hence a new check would be nice to detect accidental usage of these APIs:

  • FileWriter()
  • FileReader()
  • InputStreamReader(InputStream)
  • OutputStreamWriter(OutputStream)
  • String.getBytes()
  • String(byte[])
  • String(byte[], int, int)
  • Scanner(InputStream)
  • Scanner(File)
  • Scanner(ReadableByteChannel)

Note: Method signatures are complete, i.e. getBytes() does not mean to refer to getBytes(String).


  • All constructors for FileWriter and FileReader should be banned, as they all use default encoding, and there isn't a default constructor.

    There are several overloaded function calls which cannot be distinguished by name and parameter count alone:
    String(byte[]) vs. String(char[]), String(StringBuilder), ...
    String(byte[], int, int) vs. String(char[], int, int), String(int[], int, int)
    Scanner(InputStream), Scanner(File), Scanner(ReadableByteChannel) vs. Scanner(Readable), Scanner(String)

    To distinguish these overloaded calls, type information is required. I see several possibilities:
    1. Don't warn about those overloaded functions at all
    2. Simple type inference, will give no or wrong answers in some cases
    3. Full type inference, will require quite a lot of work
    4. Examine class files, not source files, e.g. using BCEL

    I'm in favor of #4, as it's the least amount of work, will allow an easy, straight-forward and robust check, and having a working BCEL framework in checkstyle would be useful in other cases as well.

    As the contributed BCEL code doesn't conform to the checkstyle 5 API, I've submitted patch #2788019 for it.
    That patch is only a partial solution, though, so some adjustments are yet required.