java io流 代码_Java IO流 文件的编码实例代码

•文件的编码

package cn.test;

import java.io.unsupportedencodingexception;

public class demo15 {

public static void main(string[] args) throws unsupportedencodingexception {

string str = "你好abc123";

byte[] b1 = str.getbytes();//转换成字节系列用的是项目默认的编码

for (byte b : b1) {

//把字节(转换成了int)以十六进制方式显示

system.out.print(integer.tohexstring(b & 0xff) + " ");

}

system.out.println("");

//utf8编码,中文占用3个字节,英文和数字占用1个字节

byte[] b2 = str.getbytes("utf8");

for (byte b : b2) {

system.out.print(integer.tohexstring(b & 0xff) + " ");

}

system.out.println("");

//gbk编码,中文占用两个字节,英文和数字占用1个字节

byte[] b3 = str.getbytes("gbk");

for (byte b : b3) {

system.out.print(integer.tohexstring(b & 0xff) + " ");

}

system.out.println("");

//java是双字节编码 utf-16be

//utf-16be编码,中文占2个字节,英文和数字也占用2个字节

byte[] b4 = str.getbytes("utf-16be");

for (byte b : b4) {

system.out.print(integer.tohexstring(b & 0xff) + " ");

}

system.out.println("");

//当字节序列是某种编码时,这时候想把字节序列变成字符串,也需要用这种编码方式,否则会出现乱码

string str1 = new string(b4);//使用项目默认的编码

system.out.println(str1);

string str2 = new string(b4, "utf-16be");

system.out.println(str2);

}

}

执行结果:

e4 bd a0 e5 a5 bd 41 42 43 31 32 33

e4 bd a0 e5 a5 bd 41 42 43 31 32 33

c4 e3 ba c3 41 42 43 31 32 33

4f 60 59 7d 0 41 0 42 0 43 0 31 0 32 0 33

o`y}abc123

你好abc123

文件就是字节序列,可以是任意编码的字节序列。

如果我们在中文机器上直接创建文本文件,那么该文本文件只认识ansi编码(中文系统下,ansi编码代表gbk编码)

好了,以上所述是小编给大家介绍的java io流 文件的编码的实例代码,希望对大家有所帮助

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值