import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
public class CharsetExample {
public static void main(String[] args) {
// 获取系统默认字符集
Charset defaultCharset = Charset.defaultCharset();
System.out.println("Default Charset: " + defaultCharset);
// 使用StandardCharsets预定义的字符集
String text = "Hello, World!";
byte[] utf8Bytes = text.getBytes(StandardCharsets.UTF_8);
byte[] iso88591Bytes = text.getBytes(StandardCharsets.ISO_8859_1);
// 将字节数组转换回字符串
String utf8String = new String(utf8Bytes, StandardCharsets.UTF_8);
String iso88591String = new String(iso88591Bytes, StandardCharsets.ISO_8859_1);
System.out.println("UTF-8 String: " + utf8String);
System.out.println("ISO-8859-1 String: " + iso88591String);
// 读取文件并指定字符集
try {
String content = new String(Files.readAllBytes(Paths.get("example.txt")), StandardCharsets.UTF_8);
System.out.println("File Content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
获取系统默认字符集:
Charset defaultCharset = Charset.defaultCharset();
System.out.println("Default Charset: " + defaultCharset);
这段代码会输出当前系统的默认字符集。
使用预定义字符集:
String text = "Hello, World!";
byte[] utf8Bytes = text.getBytes(StandardCharsets.UTF_8);
byte[] iso88591Bytes = text.getBytes(StandardCharsets.ISO_8859_1);
这里我们将字符串编码为 UTF-8 和 ISO-8859-1 字节序列。
将字节数组转换回字符串:
String utf8String = new String(utf8Bytes, StandardCharsets.UTF_8);
String iso88591String = new String(iso88591Bytes, StandardCharsets.ISO_8859_1);
将字节数组解码回字符串,确保使用正确的字符集进行解码。
读取文件并指定字符集:
try {
String content = new String(Files.readAllBytes(Paths.get("example.txt")), StandardCharsets.UTF_8);
System.out.println("File Content: " + content);
} catch (IOException e) {
e.printStackTrace();
}
从文件中读取内容,并指定使用 UTF-8 字符集进行解码。
上一篇:java获取客户端ip地址
下一篇:java枚举用法示例
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站