tinycodinglm / polyglot /polyglot-0002.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
1.67 kB
opencode trace
System You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

User

How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the Java version.

Assistant

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).

java
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class Filestats {
    public static void main(String[] args) throws Exception {
        String text = "Olá mundo! Ação, coração.\nSegunda linha: Straße, 你好.\n";
        Path p = Paths.get("sample.txt");
        Files.writeString(p, text, StandardCharsets.UTF_8);
        String data = Files.readString(p, StandardCharsets.UTF_8);
        long bytes = data.getBytes(StandardCharsets.UTF_8).length;
        long chars = data.codePointCount(0, data.length());
        long words = data.trim().split("\\s+").length;
        long lines = data.strip().split("\n").length;
        System.out.println("lines=" + lines + " words=" + words + " chars=" + chars + " bytes=" + bytes);
        if (lines != 2 || words != 8) throw new AssertionError("count mismatch");
        if (!(bytes > chars)) throw new AssertionError("expected multibyte content");
    }
}