三十五、Java基础之字节流文件(FileInputStream与FileOutputStream,BufferedInputStream与BufferedOutputStream,DataInputStream与DataOutputStream,ObjectOutputStream与ObjectInputStream,FileReader与FileWriter)

一、认识字节流-FileInputStream

/**
 * @author:csjin
 * 创建日期:2019-08-10-11:14
 *
 *
 * IO流
 *      流是有起点和终点的有序字节序列
 * 分类
 *      输入流/输出流:当前程序为参照,如果程序从外部获取数据到程序中来就是输入流,把程序中的数据保存到外面就是输出流
 *      字节流/字符流:如果是以字节为单位处理流中的数据就是字节流,如果是以字符为单位处理流中的数据就是字符流
 *      节点流/处理流:如果直接从数据源读写数据就是节点流,处理流就是对节点流的包装
 *
 *
 * 在程序中,经常需要读写文件中的数据,需要使用IO流,Java在java.io包中定义了相关的流类,这些类如果是以Stream单词结尾就是字节流,如果是以Reader结尾就是
 * 字符流,如果是以Writer结尾就是字符输出流
 *
 * 读写文件的步骤:
 *
 * FileInputStream/FileOutputStream:使用这两个类可以读写文件内容,是以字节为单位
 */
public class Test01 {

    public static void main(String[] args) throws IOException {

        //1、在当前程序与指定的的文件之间建立交流通道
        FileInputStream fis = new FileInputStream("/Users/myworkspsace/StudentPro/abc.txt");
        //2、读写文件数据
        int cc=0;
        while(cc !=-1) {
            cc = fis.read();
            //System.out.print(cc +" ");}//把读到的字节打印到屏幕上,65 97 98 99 70 -1
            System.out.print((char) cc + " ");//当前文件都是英文字节,一个字符对应一个字节,把读到的字节转化成字符打印到屏幕上,A a b c F
        }
        //3、关闭流通道
        fis.close();

    }
}

二、异常处理

import java.io.FileInputStream;
import java.io.IOException;

/**
 * 异常处理
 * @author:csjin
 * 创建日期:2019-08-10-16:27
 */
public class Test03 {
    public static void main(String[] args) {
        readData1();//以字节为单位读取文件内容,异常处理,手动关闭流
        readData2();//以字节数组为单位读取文件内容,异常处理,自动关闭流
    }

    private static void readData2() {

        try (
                FileInputStream fis = new FileInputStream("/Users/myworkspsace/StudentPro/abc.txt");
        ) {
            byte[] bytes = new byte[8];
            int len=fis.read(bytes);
            while (len !=-1) {
                System.out.println(new String(bytes,0,len));
                len=fis.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readData1() {

        FileInputStream fis = null;
        try {
            fis = new FileInputStream("/Users/myworkspsace/StudentPro/abc.txt");

            int cc = fis.read();
            while (cc !=-1){
                System.out.print((char)cc+" ");
                cc=fis.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fis !=null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

三、FileOutPutStream

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * FileOutPutStream,把程序中的数据保存到文件中
 *
 *
 */

public class Test05 {

    public static void main(String[] args) throws IOException {

        //1、建立当前程序与文件之间的流通道,如果文件不存在,自动创建文件,如果已存在,覆盖原有内容

        //FileOutputStream fos = new FileOutputStream("/Users/chushujin/chushujin/photo/output.txt");
        //1、建立当前程序与文件之间的流通道,如果文件不存在,自动创建文件,如果已存在,原有内容后追加新内容
        FileOutputStream fos = new FileOutputStream("/Users/photo/output.txt",true);

        //2、把数据保存到文件中
        //2-1 可以一次保存一个字节
        fos.write(97);
        fos.write(98);
        fos.write(99);
        fos.write('\n');
        //2-2一次保存一个字节数据
        byte[] bytes="wo ai zhong guo".getBytes();
        fos.write(bytes);
        //2-3换行,windows系统中需要\r \n配合使用
        fos.write('\n');

        //2-4保存部分字节数据
        fos.write(bytes,0,5);

        //3、关闭流通道
        fos.close();

    }
}

四、以字节流实现文件复制

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 以字节流实现文件复制
 *
 */
public class Test06 {

    public static void main(String[] args){

        String srcFile="/Users/photo/java.java";
        String destFile="/Users/photo/myjava.java";

//        copyFile1(srcFile,destFile);//以字节为单位,复制,异常处理,手动关闭字节流
        copyFile2(srcFile,destFile);//以字节数组为单位,复制,异常处理,自动关闭字节流

        
        
    }

    private static void copyFile2(String srcFile, String destFile) {

        try (

                FileInputStream fis = new FileInputStream(srcFile);
                FileOutputStream fos = new FileOutputStream(destFile);

                ){


            byte[] bytes = new byte[1024];
            int len = fis.read(bytes);
            System.out.println(len);

            while (len !=-1 ){

                fos.write(bytes,0,len);

                len=fis.read(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    //以字节为单位,复制,异常处理,手动关闭字节流
    private static void copyFile1(String srcFile, String destFile) {

        FileInputStream fis = null;//建立流通道
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);

            int cc = fis.read();//从源文件中读取一个字节

            while (cc !=-1){
                //把读到的字节保存到新文件中
                fos.write(cc);
                //继续读源文件的下一个字节
                cc=fis.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis !=null){

                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭流通道

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


    }
}

 五、BufferedInputStream与BufferedOutputStream

import java.io.*;

/**
 * 字节缓冲流
 * BufferedInputStream和BufferedOutputStream
 *
 */

public class Test01 {

    public static void main(String[] args){

        //读取字节缓冲流
        readData1();


        //使用字节流缓冲保存到文件
        writeData1();


    }

    private static void writeData1() {
        BufferedOutputStream bos= null;

        try {
            //在当前程序与指定文件之间建立字节流通道
            OutputStream os = new FileOutputStream("/Users/chushujin/chushujin/photo/bos.txt");

            //使用字节流缓冲对os字节流进行包装,
            bos = new BufferedOutputStream(os);

            //使用缓冲流保存数据,现在是把数据保存到缓冲流中
            bos.write(97);

            //换行
            bos.write('\r');
            bos.write('\n');

            //
            byte[] bytes ="wo ai zhong guo ".getBytes();

            bos.write(bytes);

            //把缓冲区中的数据清到文件中
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos!=null) {
                try {
                    //关闭当前流
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }



    }

    private static void readData1(){
        BufferedInputStream bis = null;

        try {
            //创建流通道
            InputStream in = new FileInputStream("/Users/chushujin/chushujin/photo/input.txt");

            //对字节流进行缓冲
            bis = new BufferedInputStream(in);

            int len = bis.read();

            while(len != -1){

                System.out.print((char)len);
                len=bis.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

 

六、DataInputStream与DataOutputStream

import java.io.*;

/**
 * DataInputStream与DataOutputStream
 * 可以读写带有数据格式的数据
 *
 */

public class Test01 {


    public static void main(String[] args){

        //1、保存数据
        writeData();

        //2、读取数据
        readData();
    }

    private static void readData() {

        DataInputStream dis = null;
        try {
            InputStream in = new FileInputStream("/Users/chushujin/chushujin/photo/out.txt");


            dis = new DataInputStream(in);

            int i = dis.readInt();
            double dd = dis.readDouble();
            boolean bb = dis.readBoolean();
            String ss = dis.readUTF();
            System.out.println("i="+i+"\n"+"dd="+dd+"\n"+"bb="+bb+"\n"+"ss="+ss);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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


    }

    //使用DataOutputStream保存数据
    private static void writeData() {

        DataOutputStream dos = null;
        try {
            OutputStream out = new FileOutputStream("/Users/chushujin/chushujin/photo/out.txt");

            dos = new DataOutputStream(out);

            dos.writeInt(123);
            dos.writeDouble(12.12);
            dos.writeBoolean(true);
            dos.writeUTF("wo ai zhong guo");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

输出

i=123
dd=12.12
bb=true
ss=wo ai zhong guo

 七、ObjectOutputStream与ObjectInputStream

新建Person类

import java.io.Serializable;

/**
 * Person类对宪法如果想实现序列话,必须实现Serializable接口
 *      Serializable是一个标志接口,没有任何方法
 */

public class Person  implements Serializable {

    private String name;
    private int age;

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

    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;
    }
}

 

 

1.ObjectOutputStream序列化:把对象序列化,就是把对象保存到文件中

import java.io.*;

/**
 * ObjectOutputStream序列化
 *
 */

public class Test01 {

    public static  void main(String[] args) throws IOException {

        Person zhangsan = new Person("zhangsan",18);

        // 把对象序列化,就是把张三对象保存到文件中
        OutputStream out = new FileOutputStream("/Users/chushujin/chushujin/photo/zhangsan.txt");

        ObjectOutputStream oos = new ObjectOutputStream(out);

        oos.writeObject(zhangsan);

        oos.close();


    }
}


2.ObjectInputStream反序列化:就是把文件中的对象读取到程序中
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

/**
 *
 *ObjectInputStream反序列化
 */

public class Test02 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        InputStream in = new FileInputStream("/Users/chushujin/chushujin/photo/zhangsan.txt");

        ObjectInputStream ois = new ObjectInputStream(in);

        Object obj = ois.readObject();//从文件中读取一个对象,readObject()方法返回值是一个Object类型的对象,
        //文件中实际存储的是Person,使用obj引用只想Person对象
        System.out.println(obj);//Person{name='zhangsan', age=18}

        ois.close();

/**
* 在对象序列化后,即把对象保存到文件中了,又在Person中添加了一个字段,修改了Person类的结构
* 再进行反序列化,出现了异常:
*
* java.io.InvalidClassException: com.csjin.edu.TestFilerStream.TestObjectfilterStream.Person;local class incompatible:
* stream classdesc serialVersionUID = -6781942565015471867,
* local class serialVersionUID = -616516252372739657
*
* 分析原因:
* 流中描述文件的serialVersionUID与本地文件的serialVersionUID不相等导致的
*
* 解决办法:
* 在Person中手动添加一个serialVersionUID值即可
*/

//Person{name='zhangsan', age=18, gender='null'}
} }

 八、FileReader与FileWriter

1.FileReader 字符流:使用FileReader读取本地文件,一次一个字符

import java.io.FileReader;
import java.io.IOException;

/**
 *FileReader 字符流
 *
 * 1、只能读取纯文本文件
 * 2、要求 文本文件的编码与当前环境的编码兼容
 */

public class Test01 {

    public static void main(String[] args){

        //使用FileReader读取本地文件,一次一个字符
        readerData1();

        //使用FileReader读取本地文件,一次一个数组
        readerData2();


    }

    //使用FileReader读取本地文件,一次一个数组
    private static void readerData2() {

        FileReader fr = null;
        try {
            fr = new FileReader("/Users/photo/myjava.java");

            char[] content = new char[8];

            int len = fr.read(content);

            while(len != -1){

                System.out.print(new String(content,0,len));
                len = fr.read(content);

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


    }

    //使用FileReader读取本地文件,一次一个字符
    private static void readerData1() {

        FileReader fr = null;
        try {
            fr = new FileReader("/Users/photo/myjava.java");

            //read读取字符,返回字符的码值,读到文件末尾返回-1
            int cc = fr.read();

            while( cc != -1){

                System.out.print((char)cc);
                cc = fr.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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



    }
}
2.FileWriter字符流:一次写一个字符到本地文件
import java.io.FileWriter;
import java.io.IOException;

/**
 * FileWriter字符流
 * 把文本保存到文本文件中,该文本要与当前环境兼容,
 */
public class Test02 {

    public  static void main(String[] args){

        writeData1();
    }

    private static void writeData1() {

        FileWriter fw = null;
        try {
            fw = new FileWriter("/Users/photo/log.txt");

            //一次写一个字符
            fw.write('A');
            fw.write("\r\n");

            fw.write('中');
            fw.write("\r\n");

            char[] content ="wo ai zhong guo ".toCharArray();
            fw.write("\r\n");

            fw.write(content);
            fw.write("\r\n");
            fw.write("我是中国人");

            fw.write("\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

3.使用FileReader/FileWriter实现文件的复制

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 使用FileReader/FileWriter实现文件的复制
 *
 */
public class Test03 {

    public static void main(String[] args){

        String srcfile="/Users/photo/java.java";
        String destfile="/Users/photo/javaauto.txt";

        //一次复制一个字符,异常处理,手动关闭流
        copyFile1(srcfile,destfile);
        //一次复制一个数组,异常处理,自动关闭流
        copyFile2(srcfile,destfile);
    }
    //一次复制一个数组,异常处理,自动关闭流
    private static void copyFile2(String srcfile, String destfile) {

        try (
                FileReader fr = new FileReader(srcfile);
                FileWriter fw = new FileWriter(destfile);

                ){


            char[] contects = new char[8];

            int len = fr.read(contects);

            while (len != -1){

                fw.write(new String(contects,0,len));
                len = fr.read(contects);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //一次复制一个字符,异常处理,手动关闭流
    private static void copyFile1(String srcfile, String destfile) {

        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader(srcfile);
            fw = new FileWriter(destfile);

            int ss = fr.read();

            while(ss != -1){

                fw.write(ss);
                ss = fr.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

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



    }
}

九、InputStreamReader 与 OutputStreamWriter

InputStreamReader:可以把字节流,以指定的编码转化为字符流

OutputStreamWriter:可以把字符流,以指定的编码转化为字节流

import java.io.*;

/**
 *InputStreamReader 与 OutputStreamWriter
 */

public class Test04 {

    public static void main(String[] args){

        readData1();

        writeData2();
    }

    private static void writeData2() {

        OutputStreamWriter osw = null;
        try {
            OutputStream out = new FileOutputStream("/Users/photo/log.txt",true);

            osw = new OutputStreamWriter(out,"utf-8");

            osw.write("123");
            osw.write('A');
            osw.write("wo ai zhong guo");
            osw.write("\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (osw!=null) {
                try {
                    osw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }

    private static void readData1() {

        InputStreamReader ism = null;
        try {
            //在当前程序与java.java之间建立流通道,java.java文件使用编码为utf-8,当前环境为utf-8
            InputStream in = new FileInputStream("/Users/photo/java.java");
            //使用字节流,将字节流fr按照指定编码转换为字符
            ism = new InputStreamReader(in, "utf-8");

            int len = ism.read();
            while (len != -1){

                System.out.print((char)len);
                len = ism.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ism != null) {
                try {
                    ism.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 十、BufferedReader 与 BufferedWriter 缓冲流

import java.io.*;
import java.util.Scanner;

/**
 * BufferedReader 与 BufferedWriter  缓冲流
 */

public class Test05 {

    public  static void main(String[] args) throws IOException {

        //使用缓冲流读取数据
        readData1();

        //使用缓冲流保存文件
        writeData2();

        writeData3();


    }

    private static void writeData3() throws IOException {

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("/Users/photo/log.txt"),"utf-8");

        BufferedWriter bw = new BufferedWriter(out);

        bw.write('A');
        bw.newLine();//换行
        bw.write("wo ai zhong guo ");

        //使用从键盘读数据
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();

        while(line.length()>0){

            bw.write(line);
            bw.newLine();
            line = br.readLine();
        }


        bw.close();
    }

    private static void writeData2() throws IOException {

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("/Users/photo/log.txt"),"utf-8");

        BufferedWriter bw = new BufferedWriter(out);

        bw.write('A');
        bw.newLine();//换行
        bw.write("wo ai zhong guo ");

        //从键盘读数据
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();

        while(line.length()>0){

            bw.write(line);
            bw.newLine();
            line = sc.nextLine();
        }


        bw.close();



    }

    private static void readData1() throws IOException {

        //创建字符流
        InputStreamReader in = new InputStreamReader(new FileInputStream("/Users/photo/java.java"),"utf-8");
        //对字符流进行缓冲
        BufferedReader br = new BufferedReader(in);

        //从缓冲流中读取数据,readLine()从缓冲流中读取一行,读到文件末尾,返回null
        String len = br.readLine();
        while (len != null){

            System.out.println(len);
            len = br.readLine();
        }

        br.close();
    }
}

 

posted @ 2019-09-20 11:29  旅行没有终点  阅读(535)  评论(0)    收藏  举报