Java IO中的其他流的使用

2021-04-06  本文已影响0人  程序员汪汪

本文主要介绍Java IO中的其他几种流:

标准输入、输出流

简介

System.in:标准的输入流,默认从键盘输入。

System.out:标准的输出流,默认从控制台输出。

主要方法

System类的setIn(InputStream is)方式重新指定输入的流。

System类的setOut(PrintStream ps)方式重新指定输出的流。

使用示例

从键盘输入字符串,要求将读取到的整行字符串转成大写输出。然后继续进行输入操作,直至当输入e或者exit时,退出程序。

设计思路

方法一:使用Scanner实现,调用next()返回一个字符串。

方法二:使用System.in实现。System.in ---> 转换流 ---> BufferedReaderreadLine()

public class OtherStream {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            // System.in:为InputStream类型,读取从键盘输入的字符串,使用转换流
            InputStreamReader isr = new InputStreamReader(System.in);
            br = new BufferedReader(isr);

            while (true) {
                System.out.println("请输入字符串:");
                String data = br.readLine();
                
                if ("e".equalsIgnoreCase(data) || "exit".equalsIgnoreCase(data)) {
                    System.out.println("程序结束");
                    break;
                }
                
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

小练习

设计实现Scanner

public class MyInput {
    // 从键盘读取字符串
    public static String readString() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 声明并初始化字符串
        String string = "";

        // 从键盘获取字符串
        try {
            string = br.readLine();

        } catch (IOException ex) {
            System.out.println(ex);
        }

        // 返回从键盘获取的字符串
        return string;
    }

    // 从键盘读取一个int值
    public static int readInt() {
        return Integer.parseInt(readString());
    }

    // 从键盘读取double值
    public static double readDouble() {
        return Double.parseDouble(readString());
    }

    // 从键盘读取byte值
    public static double readByte() {
        return Byte.parseByte(readString());
    }

    // 从键盘读取short值
    public static double readShort() {
        return Short.parseShort(readString());
    }

    // 从键盘读取long值
    public static double readLong() {
        return Long.parseLong(readString());
    }

    // 从键盘读取float值
    public static double readFloat() {
        return Float.parseFloat(readString());
    }
}

打印流

PrintStreamPrintWriter说明:

public class OtherStreamTest {
    // 打印流
    @Test
    public void test() {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\io\\hello.txt"));
            // 创建打印输出流,设置为自动刷新模式(写入换行符或字节‘\n’时都会花心缓冲区)
            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(); // 换行
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
    }
}

数据流

DataInputStreamDataOutputStream 作用: 用于读取或写出基本数据类型的变量或字符串

示例代码:

将内存中的字符串、基本数据类型的变量写出到文件中。

@Test
public void test2() {
    DataOutputStream dos = null;
    try {
        // 1.创建对象
        dos = new DataOutputStream(new FileOutputStream("D:\\io\\data.txt"));

        // 2.数据输出
        dos.writeUTF("Bruce");
        dos.flush();    // 刷新操作,将内存的数据写入到文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 3.关闭流
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

/*
注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致!
 */
@Test
public void test3() {

    DataInputStream dis = null;
    try {
        // 1.创建对象
        dis = new DataInputStream(new FileInputStream("D:\\io\\data.txt"));
        // 2.从文件中读入数据,读取的顺序要和当初写入时一致
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();
        System.out.println("name: " + name);
        System.out.println("age: " + age);
        System.out.println("isMale: " + isMale);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 3. 关闭资源
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

对象流

ObjectInputStreamObjectOutputStream

作用

对象的序列化

实现序列化的对象所属的类需要满足

  1. 需要实现接口:Serializable(标识接口)
  2. 当前类提供一个全局常量:serialVersionUID(序列版本号)
  3. 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

补充:ObjectOutputStreamObjectInputStream不能序列化statictransient修饰的成员变量

对象流的使用

序列化代码实现

要求被序列化对象必须实现序列化

@Test
public void test1() {
    ObjectOutputStream oos = null;
    try {
        // 1.创建对象,创建流
        oos = new ObjectOutputStream(new FileOutputStream("D:\\io\\object.dat"));

        // 2.操作流
        oos.writeObject(new String("亿贫如洗王道长"));
        oos.flush(); // 刷新操作

        oos.writeObject(new Person("冯宝宝", 18));
        oos.flush();

        oos.writeObject(new Person("王也", 18));
        oos.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 关闭流
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Person类:

public class Person implements Serializable { // 不实现Serializable接口不能序列化
    private static final long serialVersionUID = -7226360431328584153L;

    private String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

反序列化代码实现

@Test
public void test2() {
    ObjectInputStream ois = null;
    try {
        ois = new ObjectInputStream(new FileInputStream("D:\\io\\object.dat"));
        Object obj = ois.readObject();
        String str = (String) obj;

        Person p1 = (Person) ois.readObject();
        Person p2 = (Person) ois.readObject();

        System.out.println(str);
        System.out.println(p1);
        System.out.println(p2);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

任意存取文件流

RandomAccessFile的使用

简介

构造器

public RandomAccessFile(File file,String mode)

public RandomAccessFile(String name,String mode)

使用说明

  1. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
  2. 如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
  3. 可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。借助seek(int pos)方法
  4. 创建RandomAccessFile类实例需要指定一个mode参数,该参数指定RandomAccessFile的访问模式:
    • r:以只读方式打开
    • rw:打开以便读取和写入
    • rwd:打开以便读取和写入;同步文件内容的更新
    • rws:打开以便读取和写入;同步文件内容和元数据的更新
  5. 如果模式为只读r,则不会创建文件,而是会去读取一个已经存在的文件,读取的文件不存在则会出现异常。如果模式为rw读写,文件不存在则会去创建文件,存在则不会创建。

使用示例

文件的读取和写出操作

@Test
public void test1() {

    RandomAccessFile raf1 = null;
    RandomAccessFile raf2 = null;
    try {
        //1.创建对象,创建流
        raf1 = new RandomAccessFile(new File("test.jpg"),"r");
        raf2 = new RandomAccessFile(new File("test1.jpg"),"rw");
        //2.操作流
        byte[] buffer = new byte[1024];
        int len;
        while((len = raf1.read(buffer)) != -1){
            raf2.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.关闭流
        if(raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(raf2 != null){
            try {
                raf2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

使用RandomAccessFile实现数据的插入效果

@Test
public void test2() {
    RandomAccessFile raf1 = null;
    try {
        raf1 = new RandomAccessFile(new File("D:\\io\\hello.txt"), "rw");

        raf1.seek(3); // 将指针调到角标为3的位置
        // 方式一:保存指针3后面的所有数据到StringBuilder中
        //            StringBuilder builder = new StringBuilder((int) new File("D:\\io\\hello.txt").length());
        //            byte[] buffer = new byte[1024];
        //            int len;
        //            while ((len = raf1.read(buffer)) != -1) {
        //                builder.append(new String(buffer, 0, len));
        //            }
        //            // 将指针调回角标为3的位置
        //            raf1.seek(3);
        //            // 写入"xyz"
        //            raf1.write("xyz".getBytes());
        //            // 从“xyz”的后面开始,将StringBuilder中的数据写入到文件中去
        //            raf1.write(builder.toString().getBytes());

        // 方式二
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 内部是一个数组,类似于StringBuilder
        byte[] buffer = new byte[20];
        int len;
        while ((len = raf1.read(buffer)) != -1) {
            baos.write(buffer);
        }
        // 将指针调回角标为3的位置
        raf1.seek(3);
        // 写入"xyz"
        raf1.write("xyz".getBytes());
        // 从“xyz”的后面开始,将baos中的数据写入到文件中去
        raf1.write(baos.toString().getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (raf1 != null) {
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读