EN
Java Standard Charsets UTF 8 when read or write text file (java.nio.charset.StandardCharsets.UTF_8 package, UTF8)
2 points
Quick solution
xxxxxxxxxx
1
import java.nio.charset.Charset;
2
import java.nio.charset.StandardCharsets;
3
4
public class StandardCharsetsExample {
5
6
public static void main(String[] args) {
7
8
Charset charset = StandardCharsets.UTF_8;
9
System.out.println(charset); // UTF-8
10
11
String charsetText = "UTF-8";
12
System.out.println(charsetText); // UTF-8
13
}
14
}
Output:
xxxxxxxxxx
1
UTF-8
2
UTF-8
xxxxxxxxxx
1
import java.io.*;
2
import java.nio.charset.StandardCharsets;
3
import java.nio.file.Files;
4
import java.nio.file.Paths;
5
import java.util.List;
6
7
public class StandardCharsetsExample2 {
8
9
public static void main(String[] args) throws IOException {
10
11
// read
12
List<String> lines = Files.readAllLines(Paths.get(""), StandardCharsets.UTF_8);
13
14
String text = "Hi, there!";
15
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
16
byte[] bytes2 = text.getBytes("utf8");
17
byte[] bytes3 = text.getBytes("utf-8");
18
19
// write
20
Reader reader = new InputStreamReader(
21
new FileInputStream(new File("")), StandardCharsets.UTF_8);
22
23
// we can also use String
24
Reader reader2 = new InputStreamReader(
25
new FileInputStream(new File("")), "UTF-8");
26
27
BufferedWriter reader3 = Files.newBufferedWriter(
28
Paths.get(""), StandardCharsets.UTF_8);
29
}
30
}