java IO 流(五)

2014-11-24 11:59:56 ? 作者: ? 浏览: 169
buf = new BufferedReader(new InputStreamReader(System.in)) ; // 将字节流变为字符流
String str = null ; // 接收输入内容
System.out.print("请输入内容:然后回车") ;
try{
str = buf.readLine() ; // 读取一行数据,输入没有最长限制,以分割符(通常是回车)为界
}catch(IOException e){
e.printStackTrace() ; // 输出信息
}
System.out.println("输入的内容为:" + str) ;
九, 全并流: SequenceInputStream , 即把各种流进行合并,
InputStream is1 = null ; // 输入流1
InputStream is2 = null ; // 输入流1
OutputStream os = null ; // 输出流
SequenceInputStream sis = null ; // 合并流
is1 = new FileInputStream("d:" + File.separator + "a.txt") ;
is2 = new FileInputStream("d:" + File.separator + "b.txt") ;
os = new FileOutputStream("d:" + File.separator + "ab.txt") ;
sis = new SequenceInputStream(is1,is2) ; // 实例化合并流
int temp = 0 ; // 接收内容
while((temp=sis.read())!=-1){ // 循环输出
os.write(temp) ; // 保存内容
}
sis.close() ; // 关闭合并流
is1.close() ; // 关闭输入流1`
is2.close() ; // 关闭输入流2
os.close() ; // 关闭输出流
十, 对象序列化, ObjectOutputStream, 对象序列化 ObjectInputStream, 对象反序列化
说的明白一点,当我们写了一个对象(例如类Person),需要存储时,就必须转换成二进制,这个过程就是序列化的过程
要被序列化的对象必须要实现接口Serializable,表示这个对象可以被序列化
先定义一个类:personprivate String name ; // 声明name属性,但是此属性不被序列化
public class Person implements Serializable{
private String name ; // 声明name属性,但是此属性不被序列化
private int age ; // 声明age属性
public Person(String name,int age){ // 通过构造设置内容
this.name = name ;
this.age = age ;
}
public String toString(){ // 覆写toString()方法
return "姓名:" + this.name + ";年龄:" + this.age ;
}
};
序列化过程:
public static void main(String args[]) throws Exception{
Person per[] = {new Person("张三",30),new Person("李四",31),
new Person("王五",32)} ;
ser(per) ;
Object o[] = (Object[])dser() ;
for(int i=0;i
Person p = (Person)o[i] ;
System.out.println(p) ;
}
}
public static void ser(Object obj[]) throws Exception {
File f = new File("D:" + File.separator + "test.txt") ; // 定义保存路径
ObjectOutputStream oos = null ; // 声明对象输出流
OutputStream out = new FileOutputStream(f) ; // 文件输出流
oos = new ObjectOutputStream(out) ;
oos.writeObject(obj) ; // 保存对象
oos.close() ; // 关闭
}
public static Object[] dser() throws Exception {
File f = new File("D:" + File.separator + "test.txt") ; // 定义保存路径
ObjectInputStream ois = null ; // 声明对象输入流
InputStream input = new FileInputStream(f) ; // 文件输入流
ois = new ObjectInputStream(input) ; // 实例化对象输入流
Object obj[] = (Object[])ois.readObject() ; // 读取对象
ois.close() ; // 关闭
return obj ;
}
十一, 字符编码 :乱码产生的原因就是所用编码不一到的原因
分类:iso8859-1,属于单字节编码,最多只能表示0-225字符范围,一般用在英文上
GBK/GB2312: 中文国际编码,专门用来表示汉字, 是双字节编码
udicode:java中使用的编码,最标准的一种,用16进制表示,但不兼容iso8859-1
UTF: 兼容iso8859-1,也可以表示所有的语言字符,但长度1-6个字节不等,中文常使用的编码
System.out.println("系统默认编码:" +
System.getProperty("file.encoding")) ; // 获取当前系统编码
File f = new File("f:" + File.separator + "test.txt") ; // 实例化File类
OutputStream out = new FileOutputStream(f) ; // 实例化输出流
byte b[] = "中国,你好!".getBytes("ISO8859-1") ; // 转码操作
out.write(b) ; // 保存
out.close() ; // 关闭
-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: