Languages
[Edit]
EN

Java Standard Charsets UTF 8 when read or write text file (java.nio.charset.StandardCharsets.UTF_8 package, UTF8)

2 points
Created by:
Explosssive
339

Quick solution

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class StandardCharsetsExample {

    public static void main(String[] args) {

        Charset charset = StandardCharsets.UTF_8;
        System.out.println(charset); // UTF-8

        String charsetText = "UTF-8";
        System.out.println(charsetText); // UTF-8
    }
}

Output:

UTF-8
UTF-8

Practical usage examples

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class StandardCharsetsExample2 {

    public static void main(String[] args) throws IOException {

        // read
        List<String> lines = Files.readAllLines(Paths.get(""), StandardCharsets.UTF_8);

        String text = "Hi, there!";
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
        byte[] bytes2 = text.getBytes("utf8");
        byte[] bytes3 = text.getBytes("utf-8");

        // write
        Reader reader = new InputStreamReader(
                new FileInputStream(new File("")), StandardCharsets.UTF_8);

        // we can also use String
        Reader reader2 = new InputStreamReader(
                new FileInputStream(new File("")), "UTF-8");

        BufferedWriter reader3 =  Files.newBufferedWriter(
                Paths.get(""), StandardCharsets.UTF_8);
    }
}

See also

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join