package superjail import static java lang String format import static

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package superjail;
import static java.lang.String.format;
import static java.nio.charset.Charset.forName;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Arrays;
public final class JavaCharacterSet {
private static final Charset UTF16 = forName("UTF-16");
private static final Charset UTF8 = forName("UTF-8");
private static final String UTF_TEST_STRING = "<UTF8_TEST_STRING>验证文本</UTF8_TEST_STRING>";
public static void main(String[] args) throws IOException {
String utf16 = new String("Hello, World! 你好,世界!".getBytes(UTF16), UTF16);
String utf8 = new String("Hello, World! 你好,世界!".getBytes(UTF8), UTF8);
String def = new String("Hello, World! 你好,世界!".getBytes());
try(FileWriter writer = new FileWriter("/tmp/utf8.txt")) {
writer.write(utf8);
}
try(FileWriter writer = new FileWriter("/tmp/utf16.txt")) {
writer.write(utf16);
}
try(FileWriter writer = new FileWriter("/tmp/def.txt")) {
writer.write(def);
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/utf8.txt"), UTF8))) {
String s = reader.readLine();
System.out.println(format("read utf8: %s", s));
s.chars().forEach(c-> System.out.printf("%d ", c));
System.out.println();
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/utf16.txt"), UTF16))) {
String s = reader.readLine();
System.out.println(format("read utf16: %s", s));
s.chars().forEach(c-> System.out.printf("%d ", c));
System.out.println();
}
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/def.txt")))) {
System.out.println(format("read def: %s", reader.readLine()));
}
byte[] defBytes = def.getBytes(UTF8);
byte[] testBytes = UTF_TEST_STRING.getBytes(UTF8);
ByteBuffer byteBuffer = ByteBuffer.allocate(defBytes.length + (testBytes.length << 1));
byteBuffer.put(testBytes);
byteBuffer.put(defBytes);
byteBuffer.put(testBytes);
byteBuffer.compact();
String sample = new String(byteBuffer.array(), UTF8);
if (sample.startsWith(UTF_TEST_STRING) && sample.endsWith(UTF_TEST_STRING)) {
System.out.println("utf8 test passed");
}
System.out.println(format("sample is: %s", sample));
}
}