java基础-IO流2

来源:互联网 发布:js实现三级下拉菜单 编辑:程序博客网 时间:2024/06/06 07:35

      • 流的练习
      • 数据流打印流
      • 序列化
      • RandomAccessFile

流的练习

package atguigu;import java.io.BufferedOutputStream;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import org.junit.Test;public class TestExer {    //字符流复制 test.txt 为 test1.txt    @Test    public void test4(){        BufferedReader br = null;        BufferedWriter bw = null;        try{            br = new BufferedReader(new FileReader(new File("test.txt")));            bw = new BufferedWriter(new FileWriter(new File("test2.txt")));            char[] c = new char[20];            int len;            while((len = br.read(c)) != -1){                bw.write(c, 0, len);            }        }catch(Exception e){            e.printStackTrace();        }finally{            if(bw != null){                try {                    bw.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if(br != null){                try {                    br.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    //使用字符流实现内容的读入    @Test    public void test3(){        BufferedReader br = null;        try {            br = new BufferedReader(new FileReader("test.txt"));            String str;            while((str = br.readLine()) != null){                System.out.println(str);            }        }catch (IOException e) {            e.printStackTrace();        }finally{            if(br != null){                try {                    br.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    //使用字符流实现内容的输出    @Test    public void test2(){        BufferedWriter bw = null;        try {            bw = new BufferedWriter(new FileWriter("test1.txt"));            String str = "Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言";            bw.write(str);            bw.flush();        } catch (IOException e) {            e.printStackTrace();        }finally{            if(bw != null){                try {                    bw.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    // 使用字节流实现内容的输出    @Test    public void test1() {        BufferedOutputStream bos = null;        try {            bos = new BufferedOutputStream(                    new FileOutputStream(new File("test.txt")));            String str = "Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言";            bos.write(str.getBytes());            bos.flush();        }catch (IOException e) {            e.printStackTrace();        }finally{            if(bos != null){                try {                    bos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }}

数据流、打印流

package com.atguigu.java;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintStream;import org.junit.Test;public class TestOtherStream {    @Test    public void testData1(){        DataInputStream dis = null;        try{            dis = new DataInputStream(new FileInputStream(new File("data.txt")));//          byte[] b = new byte[20];//          int len;//          while((len = dis.read(b)) != -1){//              System.out.println(new String(b,0,len));//          }            String str = dis.readUTF();            System.out.println(str);            boolean b = dis.readBoolean();            System.out.println(b);            long l = dis.readLong();            System.out.println(l);        }catch(Exception e){            e.printStackTrace();        }finally{            if(dis != null){                try {                    dis.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    //数据流:用来处理基本数据类型、String、字节数组的数据:DataInputStream DataOutputStream    @Test     public void testData(){        DataOutputStream dos = null;        try {            FileOutputStream fos = new FileOutputStream("data.txt");            dos = new DataOutputStream(fos);            dos.writeUTF("我爱你,而你却不知道!");            dos.writeBoolean(true);            dos.writeLong(1432522344);        }catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(dos != null){                try {                    dos.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    // 打印流:字节流:PrintStream 字符流:PrintWriter    @Test    public void printStreamWriter() {        FileOutputStream fos = null;        try {            fos = new FileOutputStream(new File("print.txt"));        } catch (FileNotFoundException e) {            e.printStackTrace();        }        // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)        PrintStream ps = new PrintStream(fos, true);        if (ps != null) { // 把标准输出流(控制台输出)改成文件            System.setOut(ps);        }        for (int i = 0; i <= 255; i++) { // 输出ASCII字符            System.out.print((char) i);            if (i % 50 == 0) { // 每50个数据一行                System.out.println(); // 换行            }        }        ps.close();    }}

序列化

package com.atguigu.java;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import org.junit.Test;public class TestObjectInputOutputStream {    // 对象的反序列化过程:将硬盘中的文件通过ObjectInputStream转换为相应的对象    @Test    public void testObjectInputStream() {        ObjectInputStream ois = null;        try {            ois = new ObjectInputStream(new FileInputStream(                    "person.txt"));            Person p1 = (Person)ois.readObject();            System.out.println(p1);            Person p2 = (Person)ois.readObject();            System.out.println(p2);        }catch (Exception e) {            e.printStackTrace();        }finally{            if(ois != null){                try {                    ois.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    // 对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中    @Test    public void testObjectOutputStream() {        Person p1 = new Person("小米", 23,new Pet("花花"));        Person p2 = new Person("红米", 21,new Pet("小花"));        ObjectOutputStream oos = null;        try {            oos = new ObjectOutputStream(new FileOutputStream("person.txt"));            oos.writeObject(p1);            oos.flush();            oos.writeObject(p2);            oos.flush();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } finally {            if (oos != null) {                try {                    oos.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}/* * 要实现序列化的类: 1.要求此类是可序列化的:实现Serializable接口 * 2.要求类的属性同样的要实现Serializable接口 * 3.提供一个版本号:private static final long serialVersionUID * 4.使用static或transient修饰的属性,不可实现序列化 */class Person implements Serializable {    private static final long serialVersionUID = 23425124521L;    static String name;    transient Integer age;    Pet pet;    public Person(String name, Integer age,Pet pet) {        this.name = name;        this.age = age;        this.pet = pet;    }    @Override    public String toString() {        return "Person [name=" + name + ", age=" + age + ", pet=" + pet + "]";    }}class Pet implements Serializable{    String name;    public Pet(String name){        this.name = name;    }    @Override    public String toString() {        return "Pet [name=" + name + "]";    }}
Person [name=null, age=null, pet=Pet [name=花花]]Person [name=null, age=null, pet=Pet [name=小花]]

RandomAccessFile

package com.atguigu.java;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.RandomAccessFile;import org.junit.Test;/* * RandomAccessFile:支持随机访问 * 1.既可以充当一个输入流,有可以充当一个输出流 * 2.支持从文件的开头读取、写入 * 3.支持从任意位置的读取、写入(插入) */public class TestRandomAccessFile {    //相较于test3,更通用    @Test    public void test4(){        RandomAccessFile raf = null;        try {            raf = new RandomAccessFile(new File("hello1.txt"),"rw");            raf.seek(4);            byte[] b = new byte[10];            int len;            StringBuffer sb = new StringBuffer();            while((len = raf.read(b)) != -1){                sb.append(new String(b,0,len));            }            raf.seek(4);            raf.write("xy".getBytes());            raf.write(sb.toString().getBytes());        }catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(raf != null){                try {                    raf.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    //实现插入的效果:在d字符后面插入“xy”    @Test    public void test3(){        RandomAccessFile raf = null;        try {            raf = new RandomAccessFile(new File("hello1.txt"),"rw");            raf.seek(4);            String str = raf.readLine();//efg123456//          long l = raf.getFilePointer();//          System.out.println(l);            raf.seek(4);            raf.write("xy".getBytes());            raf.write(str.getBytes());        }catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(raf != null){                try {                    raf.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    //实现的实际上是覆盖的效果    @Test    public void test2(){        RandomAccessFile raf = null;        try {            raf = new RandomAccessFile(new File("hello1.txt"),"rw");            raf.seek(4);            raf.write("xy".getBytes());        }catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(raf != null){                try {                    raf.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }    //进行文件的读、写    @Test    public void test1(){        RandomAccessFile raf1 = null;        RandomAccessFile raf2 = null;        try {            raf1 = new RandomAccessFile(new File("hello.txt"), "r");            raf2 = new RandomAccessFile(new File("hello1.txt"),"rw");            byte[] b = new byte[20];            int len;            while((len = raf1.read(b)) != -1){                raf2.write(b, 0, len);            }        } catch (FileNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }finally{            if(raf2 != null){                try {                    raf2.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if(raf1 != null){                try {                    raf1.close();                } catch (IOException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}
原创粉丝点击