Files
openide/java/java-impl/resources/inspectionDescriptions/ReadWriteStringCanBeUsed.html
2025-02-05 04:43:28 +00:00

26 lines
1.3 KiB
HTML

<html>
<body>
Reports method calls that read or write a <code>String</code> as bytes using <code>java.nio.file.Files</code>.
Such calls can be replaced with a call to a <code>Files.readString()</code> or <code>Files.writeString()</code> method introduced in Java 11.
<p><b>Example:</b></p>
<pre><code>
String s = "example";
Files.write(Paths.get("out.txt"), s.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE);
s = new String(Files.readAllBytes(Paths.get("in.txt")), StandardCharsets.ISO_8859_1);
</code></pre>
<p>After the quick fix is applied:</p>
<pre><code>
String s = "example";
Files.writeString(Paths.get("out.txt"), s, StandardOpenOption.WRITE);
s = Files.readString(Paths.get("in.txt"), StandardCharsets.ISO_8859_1);
</code></pre>
<p>
Note that the <code>readString()</code> behavior differs from the <code>new String(bytes, charset)</code> behavior when it comes to
handling of invalid (unmappable) characters. The <code>readString()</code> method throws an exception in such cases, while the
<code>new String(bytes, charset)</code> method silently replaces invalid characters with the replacement character.
If silent replacement is desired, it would be better to suppress the inspection warning.
</p>
<!-- tooltip end -->
<p><small>New in 2018.3</small></p>
</body>
</html>