Text is converted to or from bytes with the platform default charset

tx0/java:platform-charsetstrictwarningbug

What it finds

new FileReader(file), new InputStreamReader(in), text.getBytes() and new String(bytes) use the default charset of the machine they run on. Until Java 18 that depends on the operating system and locale, so the same file reads differently on another machine; the java.nio.charset documentation and JEP 400 describe the change. Passing the charset makes the conversion fixed.

Reported is getBytes() without arguments on a string, new String(bytes) with a byte array alone, and the one-argument constructors of FileReader, FileWriter, InputStreamReader and OutputStreamWriter.

From the rule's source, default_charset.rs.

Example from the rule's tests
import java.io.FileReader;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.StandardCharsets; class Text {  void read(String path, InputStream in, String text, byte[] data) throws Exception {    FileReader a = new FileReader(path);tx0 reports: without a charset uses the platform default    InputStreamReader b = new InputStreamReader(in);tx0 reports: without a charset    byte[] c = text.getBytes();tx0 reports: uses the platform default charset    String d = new String(data);tx0 reports: without a charset    InputStreamReader e = new InputStreamReader(in, StandardCharsets.UTF_8);    String f = new String(text);  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:platform-charset" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:platform-charset] reason="..."

tx0 explain tx0/java:platform-charset shows the same in the terminal. Found a false positive? Report it.