File size: 1,674 Bytes
d517dc9
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "polyglot-0002", "name": "UTF-8 file stats in Java"}
{"type": "message", "message": {"role": "system", "content": "You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations."}}
{"type": "message", "message": {"role": "user", "content": "How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the Java version."}}
{"type": "message", "message": {"role": "assistant", "content": "In Java, `String.length()` counts UTF-16 units — use `codePointCount` for characters, and always pass `StandardCharsets.UTF_8` explicitly (never rely on the platform default).\n\n```java\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.*;\n\npublic class Filestats {\n    public static void main(String[] args) throws Exception {\n        String text = \"Olá mundo! Ação, coração.\\nSegunda linha: Straße, 你好.\\n\";\n        Path p = Paths.get(\"sample.txt\");\n        Files.writeString(p, text, StandardCharsets.UTF_8);\n        String data = Files.readString(p, StandardCharsets.UTF_8);\n        long bytes = data.getBytes(StandardCharsets.UTF_8).length;\n        long chars = data.codePointCount(0, data.length());\n        long words = data.trim().split(\"\\\\s+\").length;\n        long lines = data.strip().split(\"\\n\").length;\n        System.out.println(\"lines=\" + lines + \" words=\" + words + \" chars=\" + chars + \" bytes=\" + bytes);\n        if (lines != 2 || words != 8) throw new AssertionError(\"count mismatch\");\n        if (!(bytes > chars)) throw new AssertionError(\"expected multibyte content\");\n    }\n}\n```"}}