JDK-8167648 : java.io.PrintWriter should have PrintWriter((String|File), Charset) constructors
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.io
  • Affected Version: 8,9
  • Priority: P3
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2016-10-12
  • Updated: 2017-12-02
  • Resolved: 2017-12-02
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
Other
tbd_majorResolved
Related Reports
Duplicate :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
Currently when constructing a java.io.PrintWriter, the charset can only be specified by String. This means two things:
1) I have to catch, or deal with, UnsupportedEncodingException being thrown, and
2) I cannot use the java.nio.charset.StandardCharsets constants to specify the character set that I want to use.

Of course there should be two new constructors:
java.io.PrintWriter.PrintWriter(File, Charset)
java.io.PrintWriter.PrintWriter(String, Charset)

JUSTIFICATION :
Given that I suspect a large portion of the users of this class will just want to write UTF-8, then adding these constructor overloads would make the code simpler. So, instead of:

try {
  new PrintWriter(file, "UTF-8");
} catch (UnsupportedEncodingException e) {
  // Ignore, this is required to be supported by the JVM.
}

we could write:

new PrintWriter(file, StandardCharsets.UTF_8);

Which gets rid of the boilerplate code to deal with the exception that can never happen.

The effort to implement should be relatively minimal, as the internal constructor already expects a Charset.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
That these constructors are added.
ACTUAL -
These constructors have not yet been added.

---------- BEGIN SOURCE ----------
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.io.PrintWriter;

public class Test {
  public static int main(String []) {
    try {
      new PrintWriter("test", StandardCharsets.UTF_8);
    } catch (FileNotFoundException e) {
      // don't mind dealing with this, since it is a real thing
    }
  }
}

---------- END SOURCE ----------