专栏名称: 张风捷特烈
海的彼岸,有我未曾见证的风采。
目录
相关文章推荐
中国舞台美术学会  ·  资讯丨五部门:《优化消费环境三年行动方案(2 ... ·  2 天前  
中国日报网  ·  夜赏|灵瑞迎新 白蛇迎春 ·  2 天前  
中国日报网  ·  夜赏|灵瑞迎新 白蛇迎春 ·  2 天前  
中国舞台美术学会  ·  中国舞台美术学会(第十届)换届大会暨第十届( ... ·  3 天前  
中国舞台美术学会  ·  资讯丨第十一届当代小剧场戏曲艺术节圆满闭幕 ·  3 天前  
中国舞台美术学会  ·  聚焦丨2025年中国音乐剧市场展望:从扩张到 ... ·  3 天前  
51好读  ›  专栏  ›  张风捷特烈

Java总结IO篇之其他IO流对象

张风捷特烈  · 简书  ·  · 2018-10-12 13:34

正文

零、前言:

本篇涉及到的流:
1.PrintWriter: 字符 打印输出流
2.PrintStream: 字节 打印输出流
3.SequenceInputStream :合并多个字节输入流
4.RandomAccessFile:随机操作文件
5.ObjectOutputStream与ObjectInputStream :对象的序列化流
6.DataInputStream与DataOutputStream :基本数据类型操作流
7.ByteArrayInputStream与ByteArrayOutputStream:字节数组操作流

一、PrintWriter: 字符 打印输出流

PrintWriter.png
1.构造方法
File file 文件
File file, String csn 文件,字符集 
String fileName 文件名 
String fileName, String csn 文件名,字符集
OutputStream out 字节输出流
OutputStream out, boolean autoFlush 字节输出流,是否自动刷新缓冲区
Writer out 字符输出流
Writer out, boolean autoFlush 字符输出流,是否自动刷新缓冲区  

无论是文件也好,字符串也好,字节输出流,字符输出流也好,总之一句话:
给我一个 输出流 ,还你一个 PrintWriter

使用:键盘录入,控制台输出大写
public class PrintStreamTest {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
        //使用控制台输出流创建一个自动刷新缓冲区的PrintWriter对象
        PrintWriter pw = new PrintWriter(System.out,true);
        String line = null;
        while ((line = bfr.readLine()) != null) {
        //pw.write(line.toUpperCase());//不带换行
        //pw.flush();
            pw.println(line.toUpperCase());//自带换行,自带刷新
        }
        bfr.close();
        pw.close();
    }
}
使用:键盘录入,输出大写到文件

想要将键盘录入保存到文件中,只要将 控制台输出流 换成 文件输出流 即可
其他部分同上

String path = "I:\\Java\\Base\\Thinking\\src\\IOTest\\PrintWriter.txt";
PrintWriter pw = new PrintWriter(new FileWriter(path), true);
PrintWriter输出到文件.png

二、PrintStream: 字节 打印输出流
PrintStream.png
File file 文件
File file, String csn 文件,字符集
String fileName 文件名
String fileName, String csn 文件名,字符集
OutputStream out 字节输出流
OutputStream out, boolean autoFlush  字节输出流,是否自动刷新缓冲区
OutputStream out, boolean autoFlush, String encoding 字节输出流,是否自动刷新缓冲区,字符集

无论是文件也好,字符串也好,字节输出流,总之一句话:
给我一个 字节输出流 ,还你一个 PrintStream

public class PrintWriterTest {
    public static void main(String[] args) {
        try {
            int a = Integer.parseInt("a");
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}
java.lang.NumberFormatException: For input string: "a"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at top.toly.IO.io.其他流.PrintWriterTest.main(PrintWriterTest.java:12)

所有异常继承自:Throwable 类
其中有个不起眼的方法printStackTrace(),一般放着也没人管
但它有的重载的方法 void printStackTrace​(PrintStream s) 可以自定义输出流

public class PrintStreamTest {
    public static void main(String[] args) throws FileNotFoundException {
        try {
            int a = Integer.parseInt("a");
        } catch (NumberFormatException e) {
            e.printStackTrace();//默认是输出到控制台:即System.out流
            //将信息打印到F:\log.txt文件中
            e.printStackTrace(new PrintStream("F:\\log.txt"));
        }
    }
}
输出错误日志到文件.png

也可以加入异常的时间

//将信息打印到F:\log.txt文件中
PrintStream ps = new PrintStream("F:\\log.txt");
ps.println(new SimpleDateFormat(" G yyyy/MM/dd 星期--EE a hh:mm:ss ").format(new Date().getTime()));
e.printStackTrace(ps);//默认是输出到控制台:即System.out流

三、SequenceInputStream :合并多个字节输入流

InputStream s1, InputStream s2  两个字节流对象,先读s1,再s2
(Enumeration<? extends InputStream> e)  
1.将两个文件的数据合并到一个文件
public class SISTest {
    public static void main(String[] args) throws Exception {
        FileInputStream fis1 = new FileInputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\FileInputStream.txt");
        FileInputStream fis2 = new FileInputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\TxtInfo.ini");
        //使用Vector获取Enumeration对象
        Vector<InputStream> vec = new Vector<>();
        vec.add(fis1);
        vec.add(fis2);
        SequenceInputStream sis = new SequenceInputStream(vec.elements());//合并输入流
        //创建输出流
        FileOutputStream fos = new FileOutputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\SequenceInputStream.txt");

        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = sis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        sis.close();
        fos.close();
    }
}
SequenceInputStream.png
2.文件切分

当一个文件过大时,可以分割成多个小块
比如将一个1GB的电影分割成10份,每份100+M,由于字节不完整,导致无法播放
所以别人也不知道是什么电影 想看时用合并流合并一下,就能正常播放了。
可以搞个切合播放器,关闭播放器将电影切割,需要打开时碎片合并,然后就神不知鬼不觉。

目标文件Activity.md --7.34 KB (7,521 字节),按3KB大小切

public class SplitFile {
    public static void main(String[] args) throws Exception {
        String pathS = "I:\\Java\\Base\\Thinking\\src\\IOTest\\Activity.md";
        File fileS = new File(pathS);
        FileInputStream fis = new FileInputStream(pathS);
        //获取待切分文件名,以它作文文件夹,放入切分后的
        File parent = new File(fileS.getParentFile().getAbsolutePath()
                + File.separator + fileS.getName().split("\\.")[0]);
        parent.mkdir();
        int count = 0;
        int len = 0;
        byte[] buf = new byte[1024 * 3];//每份3kb,最后一份小于或等于3kb
        while ((len = fis.read(buf)) != -1) {
            File fileT = new File(parent, (count++) + ".temp");
            FileOutputStream fos = new FileOutputStream(fileT);
            fos.write(buf, 0, len);
            fos.close();
        }
        fis.close();
    }
}
切割文件.png

合并

public class SISTest {
    public static void main(String[] args) throws Exception {
        FileInputStream fis1 = new FileInputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\Activity\\0.temp");
        FileInputStream fis2 = new FileInputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\Activity\\1.temp");
        FileInputStream fis3 = new FileInputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\Activity\\2.temp");
        //使用Vector获取Enumeration对象
        ArrayList<InputStream> list = new ArrayList<>();
        list.add(fis1);
        list.add(fis2);
        list.add(fis3);
        //基于ArrayList合并流:需自定义Enumeration
        final Iterator<InputStream> it = list.iterator();
        Enumeration<InputStream> en = new Enumeration<>() {
            @Override
            public boolean hasMoreElements() {
                return it.hasNext();
            }
            @Override
            public InputStream nextElement() {
                return it.next();
            }
        };
        SequenceInputStream sis = new SequenceInputStream(en);//合并输入流
        //创建输出流
        FileOutputStream fos = new FileOutputStream("I:\\Java\\Base\\Thinking\\src\\IOTest\\Activity\\Activity.md");
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = sis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        sis.close();
        fos.close();
    }
}

四、对象的序列化流

使用ObjectOutputStream将对象序列化成为数据输出-->将对象持久存储
使用ObjectInputStream进行读取序列化的数据-->恢复先前对象
只能序列化堆中的对象,static修饰的成员变量不能被序列化
transient修饰的成员变量,即使在堆内存中也不会被序列化

1、ObjectOutputStream :对象的序列化输出流
 private static void writeObject() throws IOException {
     String path = "I:\\Java\\Base\\Thinking\\src\\IOTest\\ObjectOutputStream.txt";
     ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path));
     //Person需要序列化implements Serializable:否则ERROR----NotSerializableException
     Person toly = new Person("捷特", 24);
     oos.writeObject(toly);
     oos.close();
 }
public class Person implements Serializable {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //get()、set()、toSring()省略
}
将对象序列化到文件中.png
2、ObjectInputStream :对象的序列化输入流

相当于给个文件给你,你直接读出来一个对象,创建,赋值什么的都已经搞定了
对于十分复杂的对象序列化还是很方便的,但由于是IO,相对比较耗时

private static void readObject() throws IOException, ClassNotFoundException {
    String path = "I:\\Java\\Base\\Thinking\\src\\IOTest\\ObjectOutputStream.txt";
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
    Person toly = (Person) ois.readObject();
    System.out.println(toly);//Person{name='捷特', age=24}

五、RandomAccessFile:随机操作文件

1.该类不是算是IO体系中子类。而是直接继承自Object。
2.但是它是IO包中成员。因为它具备读和写功能,内部封装字节输入流和输出流。
3.内部封装数组,通过指针对数组的元素进行操作,getFilePointer获取指针位置,通过seek改变指针的位置
4.只能操作磁盘文件,

构造方法:
File file, String mode     rw :读写模式   r : 只读 
String name, String mode    

1.文件写入
public class RAF_Test {
    public static void main(String[] args) throws IOException {
        String path = "I:\\\\Java\\\\Base\\\\Thinking\\\\src\\\\IOTest\\RandomAccessFile.txt";

        RandomAccessFile raf = new RandomAccessFile(path, "rw");
        raf.write("张风捷特烈".getBytes());
        raf.write(38);
        raf.write(527654);
        raf.close();
    }
}
RandomAccessFile.png

可见38和527654两个int值以 & 字符展现出来,utf-8码表第38为是 & 这情有可原,527654怎么也来插一脚
众所周知,一个int占4个字节,一个字节是8位,也就是一个int占32位,转换成二进制即下面:

3366
0000 0000 0000 1000 0000 1101 0010 0110
38
0000 0000 0000 0000 0000 0000 0010 0110
RandomAccessFile写入时int只写入低8位(因为字符写入,一次只能写一个字节即8位),即0010 0110

解决方法:将一个int分为4次来读,每次读一个字节(8位),写入文件

raf.writeInt(527654);//RandomAccessFile内部已经封装
RandomAccessFile2.png
2.读取
RandomAccessFile rafR = new RandomAccessFile(path, "r");
        byte[] buf = new byte[9];//一个utf-8汉字占三个字节,这里一次读三个汉字
        rafR.read(buf);
        System.out.println(new String(buf));//张风捷
        //这里用8,因为两个汉字3*2=6字节,加上2个&&一共8个字节。
        byte[] buf2 = new byte[8];
        rafR.read(buf2);
        System.out.println(new String(buf2));//特烈&&
        //读取int值:如果上面不是8,而是9,那么527654的字节就不完整,会报错
        System.out.println(rafR.readInt());//527654
字节显示.png
3.seek调节指针读取
RandomAccessFile rafR = new RandomAccessFile(path, "r");
rafR.seek(3);//将读取的指针移到第4个字节
byte[] buf = new byte[3];
rafR.read(buf);
System.out.println(new String(buf));//风
4.seek调节指针写出
String path = "I:\\\\Java\\\\Base\\\\Thinking\\\\src\\\\IOTest\\RandomAccessFile.txt";
RandomAccessFile rafRW = new RandomAccessFile(path, "rw");
rafRW.write("张风捷特".getBytes());
rafRW.write(38);
rafRW.write(527654);
rafRW.writeInt(527654);
rafRW.seek(40);
rafRW.write("巫缨".getBytes());
rafRW.close();






请到「今天看啥」查看全文