六、转换流的字符编码

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

一、对象序列化1.1、对象序列化

被操作的对象需要实现Serializable接口

1.2、对象序列化流ObjectOutputStream与ObjectInputStream

ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化。

ObjectOutputStream 和 ObjectInputStream 分别与 FileOutputStream 和 FileInputStream 一起使用时,可以为应用程序提供对对象图形的持久存储。ObjectInputStream 用于恢复那些以前序列化的对象。

抛出:InvalidClassException- 序列化操作使用的类出了问题。NotSerializableException- 某个要序列化的对象不能实现java.io.Serializable 接口。IOException- 由底层 OutputStream 抛出的任何异常。

示例一、对象序列化

packagecom.pb.io.demo7;importjava.io.Serializable;/*** 用户类

**/publicclassUserimplementsSerializable{/*** 序列号*/PRivatestaticfinallongserialVersionUID = 1031444657618620970L;privateString name;privateString passWord;privateintage;publicUser() {super();//TODO Auto-generated constructor stub}publicUser(String name, String password,intage) {super();this.name =name;this.password =password;this.age =age;

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicString getPassword() {returnpassword;

}publicvoidsetPassword(String password) {this.password =password;

}publicintgetAge() {returnage;

}publicvoidsetAge(intage) {this.age =age;

}publicvoidshow(){

System.out.println("姓名:"+this.name+",年龄:"+this.age+",密码:"+this.password);

}

}

packagecom.pb.io.demo7;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;publicclassObjectStreamDemo {publicstaticvoidmain(String[] args) {

File file=newFile("d:\\user.txt");

writeObj(file);

readObj(file);

}//序列化publicstaticvoidwriteObj(File file) {

System.out.println("=====开始序列化=====");//声明序列化流ObjectOutputStream oos=null;try{

oos=newObjectOutputStream(newFileOutputStream(file));//声明对象,并初始化User u=newUser("张三","123qwe",23);//序列化,写入文件oos.writeObject(u);

System.out.println("=====序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(oos!=null){

oos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}

}//反序列化publicstaticvoidreadObj(File file) {

System.out.println("=====开始反序列化=====");//声明反序列化流ObjectInputStream ois=null;try{

ois=newObjectInputStream(newFileInputStream(file));//反序列化,读出的Object,要强制类型转换User u=(User)ois.readObject();//显示属性u.show();

System.out.println("=====反序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}finally{try{if(ois!=null)

ois.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

结果:

=====开始序列化=====

=====序列化完成=====

=====开始反序列化=====姓名:张三,年龄:23,密码:123qwe=====反序列化完成=====

示例二、静态成员不能被序列化

packagecom.pb.io.demo7;importjava.io.Serializable;/*** 用户类

**/publicclassUserimplementsSerializable{/*** 序列号*/privatestaticfinallongserialVersionUID = 1031444657618620970L;privateString name;privateString password;privateintage;privatestaticString country="cn";publicUser() {super();

}publicUser(String name, String password,intage,String country) {super();this.name =name;this.password =password;this.age =age;this.country=country;

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicString getPassword() {returnpassword;

}publicvoidsetPassword(String password) {this.password =password;

}publicintgetAge() {returnage;

}publicvoidsetAge(intage) {this.age =age;

}publicvoidshow(){

System.out.println("姓名:"+this.name+",年龄:"+this.age+",密码:"+this.password+",国家:"+country);

}

}

packagecom.pb.io.demo7;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;publicclassObjectStreamDemo {publicstaticvoidmain(String[] args) {

File file=newFile("d:\\user.txt");

writeObj(file);//分开执行不能同时执行readObj(file);

}//序列化publicstaticvoidwriteObj(File file) {

System.out.println("=====开始序列化=====");//声明序列化流ObjectOutputStream oos=null;try{

oos=newObjectOutputStream(newFileOutputStream(file));//声明对象,并初始化User u=newUser("张三","123qwe",23,"天朝");//序列化,写入文件oos.writeObject(u);

System.out.println("=====序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(oos!=null){

oos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}

}//反序列化publicstaticvoidreadObj(File file) {

System.out.println("=====开始反序列化=====");//声明反序列化流ObjectInputStream ois=null;try{

ois=newObjectInputStream(newFileInputStream(file));//反序列化,读出的Object,要强制类型转换User u=(User)ois.readObject();//显示属性u.show();

System.out.println("=====反序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}finally{try{if(ois!=null)

ois.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

结果:

=====开始反序列化=====

姓名:张三,年龄:23,密码:123qwe,国家:cn

=====反序列化完成=====

示例三、transient修饰的成员不会被序列化

packagecom.pb.io.demo7;importjava.io.Serializable;/*** 用户类

**/publicclassUserimplementsSerializable{/*** 序列号*/privatestaticfinallongserialVersionUID = 1031444657618620970L;privateString name;privatetransientString password;//加上transient关键字,保护不会被序列化privateintage;publicUser() {super();

}publicUser(String name, String password,intage) {super();this.name =name;this.password =password;this.age =age;

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicString getPassword() {returnpassword;

}publicvoidsetPassword(String password) {this.password =password;

}publicintgetAge() {returnage;

}publicvoidsetAge(intage) {this.age =age;

}publicvoidshow(){

System.out.println("姓名:"+this.name+",年龄:"+this.age+",密码:"+this.password);

}

}

packagecom.pb.io.demo7;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;publicclassObjectStreamDemo {publicstaticvoidmain(String[] args) {

File file=newFile("d:\\user.txt");

writeObj(file);//分开执行不能同时执行readObj(file);

}//序列化publicstaticvoidwriteObj(File file) {

System.out.println("=====开始序列化=====");//声明序列化流ObjectOutputStream oos=null;try{

oos=newObjectOutputStream(newFileOutputStream(file));//声明对象,并初始化User u=newUser("张三","123qwe",23);//序列化,写入文件oos.writeObject(u);

System.out.println("=====序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(oos!=null){

oos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}

}//反序列化publicstaticvoidreadObj(File file) {

System.out.println("=====开始反序列化=====");//声明反序列化流ObjectInputStream ois=null;try{

ois=newObjectInputStream(newFileInputStream(file));//反序列化,读出的Object,要强制类型转换User u=(User)ois.readObject();//显示属性u.show();

System.out.println("=====反序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}finally{try{if(ois!=null)

ois.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

结果:

=====开始序列化=====

=====序列化完成=====

=====开始反序列化=====姓名:张三,年龄:23,密码:null=====反序列化完成=====

示例四、序列多个对象或者集合

Person引用以上示例三

packagecom.pb.io.demo7;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.util.ArrayList;publicclassObjectStreamDemo {publicstaticvoidmain(String[] args) {

File file=newFile("d:\\user.txt");

writeObj(file);//分开执行不能同时执行readObj(file);

}//序列化publicstaticvoidwriteObj(File file) {

System.out.println("=====开始序列化=====");//声明序列化流ObjectOutputStream oos=null;try{

oos=newObjectOutputStream(newFileOutputStream(file));//声明对象,并初始化User u1=newUser("张三","123qwe",23);

User u2=newUser("李四","456tyu",21);

User u3=newUser("王五","asdf",23);

User u4=newUser("赵六","bnme",23);

ArrayList<User> users=newArrayList<User>();

users.add(u1);

users.add(u2);

users.add(u3);

users.add(u4);//序列化,写入文件oos.writeObject(users);

System.out.println("=====序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(oos!=null){

oos.close();

}

}catch(IOException e) {

e.printStackTrace();

}

}

}//反序列化publicstaticvoidreadObj(File file) {

System.out.println("=====开始反序列化=====");//声明反序列化流ObjectInputStream ois=null;try{

ois=newObjectInputStream(newFileInputStream(file));//反序列化,读出的Object,要强制类型转换ArrayList<User> users=(ArrayList<User>)ois.readObject();//显示属性for(User u:users){

u.show();

}

System.out.println("=====反序列化完成=====");

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}finally{try{if(ois!=null)

ois.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

结果:

=====开始序列化=====

=====序列化完成=====

=====开始反序列化=====姓名:张三,年龄:23,密码:null姓名:李四,年龄:21,密码:null姓名:王五,年龄:23,密码:null姓名:赵六,年龄:23,密码:null=====反序列化完成=====

示例王、引用类型的对象序列化

packagecom.pb.io.demo7;importjava.io.Serializable;/*** 学生

**/publicclassStudentimplementsSerializable {privateString name;privateintage;publicStudent() {super();//TODO Auto-generated constructor stub}publicStudent(String name,intage) {super();this.name =name;this.age =age;

}publicvoidshow(){

System.out.println("学生姓名:"+this.name+",年龄:"+this.age);

}

}//=================packagecom.pb.io.demo7;importjava.io.Serializable;/*** 教师类

**/publicclassTeacherimplementsSerializable{/****/privatestaticfinallongserialVersionUID = 8053946921233636502L;privateString name;privateStudent stu;//引用学生引做为属性publicTeacher() {super();

}publicTeacher(String name, Student stu) {super();this.name =name;this.stu =stu;

}publicvoidshow(){

System.out.println("教师姓名:"+this.name);

stu.show();

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicStudent getStu() {returnstu;

}publicvoidsetStu(Student stu) {this.stu =stu;

}

}

packagecom.pb.io.demo7;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;publicclassObjectStreamDemo1 {publicstaticvoidmain(String[] args) {

File file=newFile("d:\\teacher.txt");

writeObj(file);//分开执行不能同时执行readObj(file);

}//序列化publicstaticvoidwriteObj(File file){

ObjectOutputStream oos=null;try{

oos=newObjectOutputStream(newFileOutputStream(file));

Student stu=newStudent("张三",21);//声明教师对象,并引用同一个学生Teacher t1=newTeacher("李老师",stu);

Teacher t2=newTeacher("王老师",stu);//序列化oos.writeObject(t1);

oos.writeObject(t2);

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(oos!=null)

oos.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}publicstaticvoidreadObj(File file){

ObjectInputStream ois=null;try{

ois=newObjectInputStream(newFileInputStream(file));//反序列化Teacher t1=(Teacher)ois.readObject();

Teacher t2=(Teacher)ois.readObject();//显示t1.show();

t2.show();//判断2个老师的学生是不是同一个学生if(t1.getStu()==t2.getStu()){

System.out.println("李老师和王老师教的是同一个学生");

}else{

System.out.println("李老师和王老师教的不是同一个学生");

}

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}finally{try{if(ois!=null)

ois.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

结果:

教师姓名:李老师

学生姓名:张三,年龄:21

教师姓名:王老师

学生姓名:张三,年龄:21

李老师和王老师教的是同一个学生

二、管道流2.1、PipedInputStream与PipedOutputStream

管道输入流应该连接到管道输出流;管道输入流提供要写入管道输出流的所有数据字节。通常,数据由某个线程从PipedInputStream对象读取,并由其他线程将其写入到相应的PipedOutputStream。不建议对这两个对象尝试使用单个线程,因为这样可能死锁线程。管道输入流包含一个缓冲区,可在缓冲区限定的范围内将读操作和写操作分离开。如果向连接管道输出流提供数据字节的线程不再存在,则认为该管道已损坏。

可以将管道输出流连接到管道输入流来创建通信管道。管道输出流是管道的发送端。通常,数据由某个线程写入PipedOutputStream对象,并由其他线程从连接的PipedInputStream读取。不建议对这两个对象尝试使用单个线程,因为这样可能会造成该线程死锁。如果某个线程正从连接的管道输入流中读取数据字节,但该线程不再处于活动状态,则该管道被视为处于毁坏状态

输入输出可以直接进行连接,通过结合多线程使用

字段摘要protected byte[]

buffer

放置传入数据的循环缓冲区。

protected

int

in

循环缓冲区中位置的索引,当从连接的管道输出流中接收到下一个数据字节时,会将其存储到该位置。

protected

int

out

循环缓冲区中位置的索引,此管道输入流将从该位置读取下一个数据字节。

protected

static int

PIPE_SIZE

管道循环输入缓冲区的默认大小。

构造方法摘要PipedInputStream()

创建尚未连接的PipedInputStream。

PipedInputStream(int pipeSize)

创建一个尚未连接的PipedInputStream,并对管道缓冲区使用指定的管道大小。

PipedInputStream(PipedOutputStream src)

创建PipedInputStream,使其连接到管道输出流src。

PipedInputStream(PipedOutputStream src,

int pipeSize)

创建一个PipedInputStream,使其连接到管道输出流src,并对管道缓冲区使用指定的管道大小。

方法摘要int

available()

返回可以不受阻塞地从此输入流中读取的字节数。

void

close()

关闭此管道输入流并释放与该流相关的所有系统资源。

void

connect(PipedOutputStream src)

使此管道输入流连接到管道输出流src。

int

read()

读取此管道输入流中的下一个数据字节。

int

read(byte[] b,

int off, int len)

将最多len个数据字节从此管道输入流读入 byte

数组。

protected

void

receive(int b)

接收数据字节。

构造方法摘要PipedOutputStream()

创建尚未连接到管道输入流的管道输出流。

PipedOutputStream(PipedInputStream snk)

创建连接到指定管道输入流的管道输出流。

方法摘要void

close()

关闭此管道输出流并释放与此流有关的所有系统资源。

void

connect(PipedInputStream snk)

将此管道输出流连接到接收者。

void

flush()

刷新此输出流并强制写出所有缓冲的输出字节。

void

write(byte[] b,

int off, int len)

将len字节从初始偏移量为off的指定 byte 数组写入该管道输出流。

void

write(int b)

将指定byte写入传送的输出流。

从类 java.io.OutputStream 继承的方法write

2.2、示例

packagecom.pb.io.demo8;importjava.io.IOException;importjava.io.PipedInputStream;publicclassReadimplementsRunnable {privatePipedInputStream pis;publicRead(PipedInputStream pis){this.pis=pis;

}

@Overridepublicvoidrun() {byte[] buf=newbyte[1024];intlen=0;try{while((len=pis.read(buf))!=-1){

String str=newString(buf,0,len);

System.out.println(str);

}

}catch(IOException e) {

e.printStackTrace();

}finally{try{if(pis!=null)

pis.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}//================packagecom.pb.io.demo8;importjava.io.IOException;importjava.io.PipedOutputStream;importjava.util.Scanner;publicclassWriteimplementsRunnable{privatePipedOutputStream pos;

Scanner input=newScanner(System.in);publicWrite(PipedOutputStream pos){this.pos=pos;

}

@Overridepublicvoidrun() {try{

System.out.println("开始写入");while(true){

String str=input.nextLine();if(str.equals("over"))

break;

pos.write(str.getBytes());

}

}catch(IOException e) {

e.printStackTrace();

}finally{try{

pos.close();

}catch(IOException e) {//TODO Auto-generated catch blocke.printStackTrace();

}

}

}

}

packagecom.pb.io.demo8;importjava.io.IOException;importjava.io.PipedInputStream;importjava.io.PipedOutputStream;publicclassDemo {publicstaticvoidmain(String[] args)throwsIOException {

PipedInputStream pis=newPipedInputStream();

PipedOutputStream pos=newPipedOutputStream();

pis.connect(pos);

Thread t1=newThread(newRead(pis));

Thread t2=newThread(newWrite(pos));

t1.start();

t2.start();

}

}

三、RandomaccessFile3.1、概述

随机访问文件,自身具备读写的方法

通过skipBytes(int x),seek(int x)来达到随机访问

此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组。存在指向该隐含数组的光标或索引,称为文件指针;输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针。写入隐含数组的当前末尾之后的输出操作导致该数组扩展。该文件指针可以通过getFilePointer方法读取,并通过seek方法设置。

mode参数指定用以打开文件的访问模式。允许的值及其含意为:

值

含意

"r"

以只读方式打开。调用结果对象的任何write方法都将导致抛出IOException。

"rw"

打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。

"rws"

打开以便读取和写入,对于"rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。

"rwd"

打开以便读取和写入,对于"rw",还要求对文件内容的每个更新都同步写入到底层存储设备。

3.2、示例

packagecom.pb.io.demo8;importjava.io.File;importjava.io.IOException;importjava.io.RandomAccessFile;publicclassRandomAccessDemo {publicstaticvoidmain(String[] args)throwsIOException {

File file=newFile("d:\\kk.txt");//write(file);read(file);

}//写入publicstaticvoidwrite(File file)throwsIOException{//声明对象,模式为读写RandomAccessFile raf=newRandomAccessFile(file,"rw");

raf.write("张三".getBytes());

System.out.println("张三".getBytes().length);//6个字节raf.writeInt(32);//4个字节//设置指针raf.seek(4*10);

raf.write("李四".getBytes());

raf.writeInt(32);//修改第一个raf.seek(0);

raf.write("赵六".getBytes());

raf.writeInt(45);

raf.close();

}//读取入publicstaticvoidread(File file)throwsIOException{//声明对象,模式为读RandomAccessFile raf=newRandomAccessFile(file,"r");byte[] buf=newbyte[6];

raf.read(buf);

String name=newString(buf);intage=raf.readInt();

System.out.println(name);

System.out.println(age);//读取指定位置的数据raf.seek(40);

raf.read(buf);

String name1=newString(buf);intage1=raf.readInt();

System.out.println(name1);

System.out.println(age1);

raf.close();

}

}

四、操作基本数据类型的流对象DataStream4.1、二进制流

数据输出流允许应用程序以适当方式将基本 Java 数据类型写入输出流中。然后,应用程序可以使用数据输入流将数据读入

数据输入流允许应用程序以与机器无关方式从底层输入流中读取基本 Java 数据类型。应用程序可以使用数据输出流写入稍后由数据输入流读取的数据。

DataInputStream 对于多线程访问不一定是安全的。 线程安全是可选的,它由此类方法的使用者负责。

4.2、示例

/*DataInputStream与DataOutputStream*/importjava.io.*;classDateStreamDemo

{publicstaticvoidmain(String[] args)throwsIOException

{

File file=newFile("d:\\data.txt");

readData(file);

}/*写入基本类行数据*/publicstaticvoidwriteData(File file)throwsIOException

{

DataOutputStream dos=newDataOutputStream(newFileOutputStream(file));

dos.writeInt(343);

dos.writeBoolean(true);

dos.writeDouble(3.14);

dos.writeUTF("您好!");

dos.close();

}/*读取基本数据类型数据*/publicstaticvoidreadData(File file)throwsIOException

{

DataInputStream dis=newDataInputStream(newFileInputStream(file));intnum=dis.readInt();booleanflag=dis.readBoolean();doubled=dis.readDouble();

String str=dis.readUTF();

System.out.println("num="+num);

System.out.println("flag="+flag);

System.out.println("d="+d);

System.out.println("str="+str);

}

}

五、ByteArrayStream5.1、概述

此类实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用toByteArray()和toString()获取数据。

关闭ByteArrayOutputStream无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException。

构造方法摘要ByteArrayOutputStream()

创建一个新的 byte 数组输出流。

ByteArrayOutputStream(int size)

创建一个新的 byte

数组输出流,它具有指定大小的缓冲区容量(以字节为单位)。

ByteArrayInputStream包含一个内部缓冲区,该缓冲区包含从流中读取的字节。内部计数器跟踪read方法要提供的下一个字节。

关闭ByteArrayInputStream无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何IOException。

构造方法摘要ByteArrayInputStream(byte[] buf)

创建一个ByteArrayInputStream,使用buf作为其缓冲区数组。

ByteArrayInputStream(byte[] buf,

int offset, int length)

创建ByteArrayInputStream,使用buf作为其缓冲区数组。

5.2、示例

/*ByteArrayInputStream:

ByteArrayOutputStream:*/importjava.io.*;classByteStreamDemo

{publicstaticvoidmain(String[] args)

{

ByteArrayInputStream bais=newByteArrayInputStream("你好,世界".getBytes());

ByteArrayOutputStream bos=newByteArrayOutputStream();intlen=0;while((len=bais.read())!=-1)

{

bos.write(len);

}

System.out.println(bos.size());

System.out.println(bos.toString());

}

}

/*ByteArrayInputStream:

ByteArrayOutputStream:*/importjava.io.*;classByteStreamDemo

{publicstaticvoidmain(String[] args)throwsIOException

{

BufferedInputStream bis=newBufferedInputStream(newFileInputStream("d:\\3.txt"));

ByteArrayOutputStream bos=newByteArrayOutputStream();

FileOutputStream fos=newFileOutputStream("d:\\y.txt");intlen=0;while((len=bis.read())!=-1)

{

bos.write(len);

}

System.out.println(bos.size());

System.out.println(bos.toString());//将内存中的数据写到输出流中bos.writeTo(fos);

fos.close();

bis.close();

}

}

六、转换流的字符编码6.1、InputStreamReader与OutputStreamReader

这2个对象在构造方法时候可以加入字符集

6.2、示例

importjava.io.*;classEncodeDemo

{publicstaticvoidmain(String[] args)throwsIOException

{

File gbk=newFile("d:\\gbk.txt");

File utf=newFile("d:\\utf.txt");//writeGBK(gbk);//writeUTF(utf);//readGBK(gbk);readUTF(utf);

}/*GBK编码写入*/publicstaticvoidwriteGBK(File gbk)throwsIOException

{

OutputStreamWriter osw=newOutputStreamWriter((newFileOutputStream(gbk)),"gbk");

osw.write("您好");

osw.close();

}/*GBK编码读取*/publicstaticvoidreadGBK(File gbk)throwsIOException

{

InputStreamReader isr=newInputStreamReader((newFileInputStream(gbk)),"gbk");char[] ch=newchar[10];intlen=isr.read(ch);

String str=newString(ch,0,len);

System.out.println(str);

isr.close();

}/*UTF-8编码写入*/publicstaticvoidwriteUTF(File utf)throwsIOException

{

OutputStreamWriter osw=newOutputStreamWriter((newFileOutputStream(utf)),"utf-8");

osw.write("您好");

osw.close();

}/*UTF-8编码读取*/publicstaticvoidreadUTF(File utf)throwsIOException

{

InputStreamReader isr=newInputStreamReader((newFileInputStream(utf)),"utf-8");char[] buf=newchar[1024];intlen=isr.read(buf);

String str=newString(buf,0,len);

System.out.println(str);

isr.close();

}

}

6.3、示例二

/*编码:String-->byte[] str.getBytes(charsetName);

解码: byte[] --->String new String(byte[],charsetName)*/importjava.util.*;classEncodeDemo1

{publicstaticvoidmain(String[] args)throwsException

{

String s="您好!";//解码byte[] buf=s.getBytes("utf-8");

System.out.println(Arrays.toString(buf));//解码String s1=newString(buf,"utf-8");

System.out.println(s1);

}

}

6.4、示例三

/*编码:String-->byte[] str.getBytes(charsetName);

解码: byte[] --->String new String(byte[],charsetName)*/importjava.util.*;classEncodeDemo1

{publicstaticvoidmain(String[] args)throwsException

{

String s="您好!";//解码byte[] buf=s.getBytes("utf-8");

System.out.println(Arrays.toString(buf));//解码 解错String s1=newString(buf,"iso8859-1");

System.out.println(s1);//再次解码String s2=newString(s1.getBytes("iso8859-1"),"utf-8");

System.out.println(s2);

}

}

6.5、示例四

packagecom.pb.io.demo9;publicclassStudentimplementsComparable<Student>{privateString name;privateintma,cn,en;privateintsum;publicStudent(String name,intma,intcn,inten) {super();this.name =name;this.ma =ma;this.cn =cn;this.en =en;this.sum = ma+cn+en;

}publicStudent() {

}publicString getName() {returnname;

}publicvoidsetName(String name) {this.name =name;

}publicintgetMa() {returnma;

}publicvoidsetMa(intma) {this.ma =ma;

}publicintgetCn() {returncn;

}publicvoidsetCn(intcn) {this.cn =cn;

}publicintgetEn() {returnen;

}publicvoidsetEn(inten) {this.en =en;

}publicintgetSum() {returnsum;

}publicvoidsetSum(intsum) {this.sum =sum;

}/*比较器方法*/@OverridepublicintcompareTo(Student stu) {intnum=newInteger(this.sum).compareTo(newInteger(stu.sum));if(num==0){returnthis.name.compareTo(stu.name);

}returnnum;

}

@OverridepublicinthashCode(){returnname.hashCode()+sum*78;

}

@Overridepublicbooleanequals(Object obj){if(!(objinstanceofStudent))thrownewClassCastException("类型不匹配");

Student s=(Student)obj;returnthis.name.equals(s.name)&&this.sum==s.sum;

}publicString toString(){return"student["+name+","+ma+","+cn+","+en;

}

}

packagecom.pb.io.demo9;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importjava.util.Comparator;importjava.util.Set;importjava.util.TreeSet;publicclassStudentTools {//获取学生信息publicstaticSet<Student> getStudents()throwsIOException {returngetStudents(null);

}//获取学生信息publicstaticSet<Student> getStudents(Comparator<Student> cmp)throwsIOException {

BufferedReader br=newBufferedReader(newInputStreamReader(System.in));//声明集合Set<Student> stus=null;//判断比较器是否为空if(cmp==null){

stus=newTreeSet<Student>();

}else{

stus=newTreeSet<Student>(cmp);

}//开始读取String line =null;

System.out.println("请输入学生姓名,数学,中文,英文成绩,中间以,分隔");while((line = br.readLine()) !=null) {if("over".equals(line)) {

break;

}

String[] info= line.split(",");

Student stu=newStudent(info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2]),

Integer.parseInt(info[3]));//添加集合stus.add(stu);

}

br.close();returnstus;

}//写入文件publicstaticvoidwriteFile(Set<Student> stus)throwsIOException{

BufferedWriter bufw=newBufferedWriter(newFileWriter("d:\\stus.txt"));//遍历写入文件for(Student s:stus){

bufw.write(s.toString()+"\t");

bufw.write(s.getSum()+"");

bufw.newLine();

bufw.flush();

}

bufw.close();

}

}

packagecom.pb.io.demo9;importjava.io.IOException;importjava.util.Collections;importjava.util.Comparator;importjava.util.Set;/*** 5个学生,每个学生有3门课成绩

* 从键盘输入以上数据(姓名,三门课成绩

* 输入的格式,如Zhangsan,30,40,60计算出总成绩

* 并把学生的信息和计算出的总分数高低顺序放在磁盘文件stud.txt

*

**/publicclassTest {publicstaticvoidmain(String[] args) {

StudentTools st=newStudentTools();//强行反转比较器Comparator<Student> cmp=Collections.reverSEOrder();//获取学生信息try{

Set<Student> stus=st.getStudents(cmp);

st.writeFile(stus);

}catch(IOException e) {

e.printStackTrace();

}

}

}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航