Skip to content

Commit a22ab5c

Browse files
committed
Experiment the Charset and String related APIs.
1 parent e9f2359 commit a22ab5c

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

Chapter13/CharsetDemo.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.nio.charset.Charset;
2+
import java.nio.ByteBuffer;
3+
4+
public class CharsetDemo{
5+
6+
public static void main(String[] args){
7+
String msg = "ξξεγβνεμ θθδμχρ";
8+
if(args.length > 0){
9+
msg = args[0];
10+
}
11+
String[] csNames = {"US-ASCII", "ISO-8859-1", "UTF-8", "UTF-16BE", "UTF-16LE", "UTF-16"};
12+
encode(msg, Charset.defaultCharset());
13+
for(String csName : csNames){
14+
encode(msg, Charset.forName(csName));
15+
}
16+
}
17+
18+
static void encode(String msg, Charset charset){
19+
System.out.println("Charset: " + charset.toString());
20+
System.out.println("Message: " + msg);
21+
22+
ByteBuffer buffer = charset.encode(msg);
23+
System.out.println("Encoded: ");
24+
25+
for(int i=0; i< buffer.limit(); i++){
26+
int _byte = Byte.toUnsignedInt(buffer.get(i));
27+
char ch = (char)_byte;
28+
if(Character.isWhitespace(ch) || Character.isISOControl(ch)){
29+
ch = '\u0000'; // empty string
30+
}
31+
System.out.printf("%2d: %02x (%c)%n", i, _byte, ch);
32+
}
33+
System.out.println();
34+
}
35+
}

Chapter13/StringCharset.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.io.UnsupportedEncodingException;
2+
3+
public class StringCharset{
4+
5+
public static void main(String[] args) throws UnsupportedEncodingException{
6+
byte[] encodedMsg = {0x66, 0x61, (byte)0xc3, (byte)0xa7, 0x61, 0x64, 0x65, 0x20, 0x74,
7+
0x6f, 0x75, 0x63, 0x68, (byte)0xc3, (byte)0xa9};
8+
System.out.println("Initial bytes length = " + encodedMsg.length);
9+
for(byte bt : encodedMsg){
10+
System.out.print(Integer.toHexString(Byte.toUnsignedInt(bt)) + " ");
11+
}
12+
System.out.println();
13+
String s = new String(encodedMsg, "UTF-8"); // with specified charset
14+
System.out.println(s);
15+
System.out.println();
16+
17+
byte[] bytes = s.getBytes(); // with default charset.
18+
System.out.println("SecondEncoded bytes length = " + bytes.length);
19+
for(byte _byte : bytes){
20+
System.out.print(Integer.toHexString(Byte.toUnsignedInt(_byte)) + " ");
21+
};
22+
System.out.println();
23+
}
24+
}

0 commit comments

Comments
 (0)