'Unable to compile code for no constuctor found for FileWriter [closed]

While I was working on one of the projects, I found that my IDE was not able to compile a piece of code which says error: no suitable constructor found for FileWriter(File,Charset)

I was wondering if this was an error how this came in the codebase at the very first place.

I am wondering if this is an issue with my IDE or am I missing something.Please help!!!



Solution 1:[1]

That constructor has only existed since JDK11. It definitely wasn't in 8. Which explains how you got there: Your IDE is configured with a compatibility level of 8, or is straight up configured to compile 'against' a JDK8.

Even so, FileWriter is an outdated concept. Try:

Path p = Paths.get("/path/to/file");
try (var writer = Files.newBufferedWriter(p)) {
}

This one:

  • Defaults to UTF-8 (unlike new FileWriter(file), which defaults to 'platform default' until JDK17, and UTF-8 from JDK18 onwards).
  • You can call newBufferedWriter(p, charset) instead if you prefer.
  • Exists since JDK8 (7, even, I think).

The JDK 1.0 version is this:

try (var fileOut = new FileOutputStream(file);
     var writer = new OutputStreamWriter(fileOut, charset)) {
...
}

And you might want to wrap that in BufferedWriter to boot.

Don't use this unless you need compatibility with JDKs that have been end-of-lifed for years at this point, i.e. - don't use this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rzwitserloot