java(IO)第二部分
一、合并流SequenceInputStream
import java.io.* ;
public class IODemo25
{
public static void main(String args[]) throws Exception
{
InputStream in1 = null ;
InputStream in2 = null ;
// 建立一个输出流
OutputStream out = null ;
in1 = new FileInputStream(new File("f:\\lxh1.txt")) ;
in2 = new FileInputStream(new File("f:\\lxh2.txt")) ;
out = new FileOutputStream(new File("f:\\lxhmldn.txt")) ;
// 此处相当于将两个文件合并了
SequenceInputStream seq = null ;
seq = new SequenceInputStream(in1,in2) ;
// 文件合并之后输出到:lxhmldn.txt文件之中
int c = 0 ;
while((c=seq.read())!=-1)
{
out.write(c) ;
}
in1.close() ;
in2.close() ;
out.close() ;
seq.close() ;
}
};
二、序列化及反序列化 Serializable
不想序列化的字段可用tansient关键字申明。Serializable是申明性接口内部没,用任何方法。
// 建立一个Person类,把Person类的对象序列化
import java.io.* ;
class Person implements Serializable
{
private String name ;
private transient int age ;
public Person(String name,int age)
{
this.name = name ;
this.age = age ;
}
public String toString()
{
return "姓名:"+this.name+",年龄:"+this.age ;
}
};
public class IODemo26
{
public static void main(String args[]) throws Exception
{
Person per = new Person("张三",30) ;
ser(per) ;
System.out.println(dser()) ;
}
// 建立一个方法用于完成对象的序列化
public static void ser(Person per) throws Exception
{
ObjectOutputStream oos = null ;
oos = new ObjectOutputStream(new FileOutputStream(new File("f:\\lxh.txt"))) ;
oos.writeObject(per) ;
oos.close() ;
}
// 反序列化
public static Person dser() throws Exception
{
ObjectInputStream ois = null ;
ois = new ObjectInputStream(new FileInputStream(new File("f:\\lxh.txt"))) ;
Object obj = ois.readObject() ;
ois.close() ;
return (Person)obj ;
}
};
3、字符集
gb2312 简体中文
GBK中文
iso8859-1国际通用编码
jvm默认的是GBK
乱码的的真正原因就是 两个操作间的编码没有统一起来!
import java.io.* ;
public class IODemo24
{
public static void main(String args[]) throws Exception
{
OutputStream out = null ;
out = new FileOutputStream(new File("f:\\lxh.txt")) ;
String str = "欢迎大家来学习。" ;
out.write(str.getBytes("GBK")) ;
//out.write(str.getBytes("ISO8859-1")) ;就会有乱码
out.close() ;
}
};
4、获取当前JVM中设置的属性等
public class IODemo23
{
public static void main(String args[])
{
// 通过此代码观察一下当前JVM中设置的属性
System.getProperties().list(System.out) ;
}
};
其他:
设置系统字符集:
System.getProperties().put("file.encooding","iso8859-1")
转换编码:
String类中的方法 getBytes()方法
附件为笔记参考内容,学习资料