文章标题 Java中io流的一些简单操作(包含文件复制,向硬盘中写入文本文件,以及io流高级应用序列化和反序列化)

来源:互联网 发布:贷款平台网站源码 编辑:程序博客网 时间:2024/06/06 14:20

这里写图片描述
package cn.io.demo;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.junit.Test;

import cn.io.entity.Student;

public class FileIo {

//字节输出流  写文件@Testpublic void testIO1() throws Exception{    FileOutputStream fos = null;    try {        fos = new FileOutputStream("F:/words.txt"); //强烈推荐这种写法 ,因为此写法兼容性更好        //像F:\\words他只是在windows支持 在Linux就不识别了  要注意!        String s = "既然选择了远方,便只顾风雨兼程...!";        byte[] b = new byte[1024];        b = s.getBytes();        int length = 0;            fos.write(b);        System.out.println("写入成功!");     } catch (Exception e) {        e.printStackTrace();    }finally{        fos.flush();        fos.close();    }}//字节输入流  FileInputStream读取文件@Testpublic void testIO2() throws Exception{    FileInputStream fis = null;    try {        fis = new FileInputStream("F:/words.txt");        byte[] b = new byte[1024];//1024kb        int length = fis.read(b);        StringBuffer stb = new StringBuffer();        while (length>0){            fis.read(b); //临时中转站   先将读取的数据保存到byte类型的数组中            stb.append(new String(b));            length = fis.read(b);        }        System.out.println(stb.toString());    } catch (Exception e) {        e.printStackTrace();    }finally{        fis.close();    }}//序列化@Testpublic void testSerializable() throws Exception{    ObjectOutputStream os = null;    try {//注意:要想一个类能够序列化,那个类必须实现Serializable接口        os = new ObjectOutputStream(new FileOutputStream("F:/student.txt"));        Student stu = new Student();        stu.setName("张三");        stu.setAge(19);        os.writeObject(stu);        System.out.println("student序列化成功!");//会出现乱码  很正常  因为写入的是二进制字节码文本    }catch (Exception e) {        e.printStackTrace();    }finally{        os.close();    }}//反序列化@Testpublic void testSerializable2() throws Exception{    ObjectInputStream ois = null;    ois = new ObjectInputStream(new FileInputStream("F:/student.txt"));    Student stu = (Student)ois.readObject();//因为该方法返回的是一个object对象,所有必须进行强制类型转换    System.out.println("姓名:"+stu.getName()+"\t年龄:"+stu.getAge());    ois.close();}

}

阅读全文
0 0
原创粉丝点击