JAVA中的字符编码操作
作者:网络转载 发布时间:[ 2013/12/24 16:42:05 ] 推荐标签:JAVA 字符编码
以下面这个代码来详细的了解这些概念
|
public class IOTest {
private static String str = "中文";
public static void main(String[] args) throws Exception {
System.out.println(System.getProperty("file.encoding"));
testChar();
printBytes(str.getBytes("utf-8"));
printBytes(str.getBytes("unicode"));
printBytes(str.getBytes("gb2312"));
printBytes(str.getBytes("iso8859-1"));
printBytes("ABC".getBytes("iso8859-1"));
byte[] bytes = {-28, -72, -83, -26, -106, -121};
System.out.println(getStringFromBytes(bytes,"utf-8"));
byte[] bytes1 = { -2,-1,78, 45, 101, -121};
System.out.println(getStringFromBytes(bytes1,"unicode"));
System.out.println(new String(bytes1));
readBytesFromFile("C:/D/charset/utf8.txt");
readBytesFromFile("C:/D/charset/gb2312.txt");
readStringFromFile("C:/D/charset/utf8.txt","utf8");
readStringFromFile("C:/D/charset/gb2312.txt","gb2312");
}
public static void testChar() throws Exception {
char c = '中';
int i = c;
System.out.println(i);
System.out.println("u4E2D");
printBytes("中".getBytes("unicode"));
}
public static void printBytes(byte[] bytes ) {
for(int i=0; i<bytes.length;i++){
System.out.print(" " + bytes[i]);
}
System.out.println("");
}
public static String getStringFromBytes(byte[] bytes,String charset ) throws Exception {
return new String(bytes,charset);
}
public static void writeTofile(byte[] bytes ) {
for(int i=0; i<bytes.length;i++){
System.out.print(" " + bytes[i]);
}
System.out.println("");
}
public static void readBytesFromFile(String fileName ) throws Exception {
File f = new File(fileName);
FileInputStream fin = new FileInputStream(f);
byte[] readBytes = new byte[10];
while (true) {
if (fin.available() >= 10) {
fin.read(readBytes);
for (byte b : readBytes) {
System.out.print(b + " ");
}
} else {
byte[] lastbits = new byte[fin.available()];
fin.read(lastbits);
for (byte b : lastbits) {
System.out.print(b + " ");
}
break;
}
}
System.out.println("");
fin.close();
}
public static void readStringFromFile(String fileName,String charset) throws Exception {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader fr = new InputStreamReader(fis,charset);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line=br.readLine()) != null){
System.out.println(line);
}
br.close();
fr.close();
fis.close();
}
}
|
Java是支持多国编码的,在Java中,字符和字符串都是以Unicode进行存储的,每个字符占两个字节
如下面的代码:
|
char c = '中';
int i = c;
System.out.println(i); //20013
System.out.println("u4E2D"); //中
printBytes("中".getBytes("unicode")); //-2 -1 78 45
|
20013对应的16进制为4E2D, 4E2D对应的10进制为78 45。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
Java性能测试有哪些不为众人所知的原则?Java设计模式??装饰者模式谈谈Java中遍历Map的几种方法Java Web入门必知你需要理解的Java反射机制知识总结编写更好的Java单元测试的7个技巧编程常用的几种时间戳转换(java .net 数据库)适合Java开发者学习的Python入门教程Java webdriver如何获取浏览器新窗口中的元素?Java重写与重载(区别与用途)Java变量的分类与初始化JavaScript有这几种测试分类Java有哪四个核心技术?给 Java开发者的10个大数据工具和框架Java中几个常用设计模式汇总java生态圈常用技术框架、开源中间件,系统架构及经典案例等

sales@spasvo.com