重温《JAVA编程思想》----2017.1.25 IO流视频

1.编码方式:

String s = "学习ABC";

byte[] b = s.getBytes();

for (byte by : b){

System.out.print(Integer.toHexString(by&0xff)+" ");

}

 

 

a.)Integer.toHexString(int i) : 16进制显示。(这里byte自动转换成int了)

b.)0xff代表二进制的11111111byte8位,当换成int的时候是32位,所以高24位为0没有用,此时与11111111进行第八位与运算,就去除了高24位。

c.)也可以 System.out.print(Integer.toHexString(by&0b11111111)+" ");

d.)0x代表16进制,0b代表二进制

e.

String s = "学习ABC";

byte[] b = s.getBytes();//我们项目默认的编码方式是UTF-8

for (byte by : b){

System.out.print(Integer.toHexString(by&0b11111111)+" ");

}

System.out.println();

//指定编码方式

byte[] another = s.getBytes("gbk");

for (byte by : another){

System.out.print(Integer.toHexString(by&0b11111111)+" ");

}

输出:

e5 ad a6 e4 b9 a0 41 42 43

d1 a7 cf b0 41 42 43

 

由输出可以看到,UTF-8中中文占3个字节,gbk中文占2个字节。

 

 

byte[] another2 = s.getBytes("utf-16be");

for (byte by : another2){

System.out.print(Integer.toHexString(by&0b11111111)+" ");

}

 

5b 66 4e 60 0 41 0 42 0 43

 

 

java是双字节编码,使用uft-16be,由输出看到,中文占2个字节,英文占2个字节。

 

 

 

f.)当你的字节序列是某种编码的时候,如果你想把你的字节序列变成字符串,那么你必须统一编码方式,否则会出乱码。

 

 

 

如下:

 

System.out.println();

String s1 = new String(another2);

System.out.println(s1);

System.out.println();

String s2 = new String(another);

System.out.println(s2);

 

 

输出:

 

 

 

 

正确做法:

 

System.out.println();

String s1 = new String(another2,"utf-16be");

System.out.println(s1);

System.out.println();

String s2 = new String(another,"gbk");

System.out.println(s2);

输出:

学习ABC

 

学习ABC

 

 

总结:当你生成字符串(new String)的时候,第一个参数是char[]或者byte[],第二个参数是编码方式,你可以通过第二个参数指定编码方式,如果不指定则使用项目默认的编码方式。

 

 

 

2.File:

a) File类用于表示文件或者目录

b) File类只用于表示文件或者目录的信息,不能用于文件内容的访问

c) 常用api如图:

File file = new File("d:\\abc.txt");

File file2 = new File("d:\\", "abcd.txt");

if(!file.exists()){

file.mkdir();//file.mkdirs()---创建多级目录

file2.createNewFile();//--------创建文件

System.out.println(file.isDirectory());

System.out.println(file.isFile());

 

}else{

file.delete();

}

 

 

 

d.) list()列出的它的子目录的名字,不包括子目录下的文件,返回字符串数组;

   listFiles()返回文件数组,通过数组可以进行很多操作。

 

 

3.RandomAccessFile

a.)Java提供的对文件内容的访问,可以读文件,也可以写文件,可以随机访问文件,可以访问文件的任意位置

b.)硬盘上的文件是byte byte byte存储的,是数据的集合

c.)打开方式有2:rw 读写     r 只读

RandomAccessFile  raf = new RandomAccessFile(file.rw)-指定方式

d.)RandomAccessFile有一个文件指针pointer,开始的时候pointer = 0;

f.)raf.write()一次只写一个字节 ,即低8位,当你写write(int i)的时候,int4字节,32位,你需要写4次,从低8位到高8位。也可以write(byte[])

g.)read()也读1个字节。

h.)读写完毕后要关闭---close()

 

 

 

4.对象的序列化和反序列化:

 

Object对象转换成byte序列就是序列化,反过来就是反序列化。

对象必须实现Serialiazable接口才能序列化,否则将出现异常。

transient关键字:不序列化

如果序列化子类的时候,父类构造函数被调用。

如果反序列化子类的时候,如果其父类没有实现序列化接口,那么父类的构造函数被显示调用。

 

猜你喜欢

转载自blog.csdn.net/mypromise_tfs/article/details/54746751
今日推荐