Java IO流

2021/5/13 20:27:18

本文主要是介绍Java IO流,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Java IO流

1.File Class

File类代表一个文件或者文件目录
构造器:

  • File(String pathname)
  • File(String pathname,String child)
  • File(String parent,String child)
    parent目录路径 child表示从parent的下一层目录
        File file = new File("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\123.txt");
        File file1=new File("123.txt");
        File file2=new File("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream","123.txt");
        File file3=new File("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd","iostream");

1.1 File类的获取方法

  • getAbsolutePath()获取绝对路径
  • getAbsoluteFile()获取绝对路径表示的文件
  • getPath()获取路径
  • getParent()获取上一层文件目录路径,若无返回null
  • length()获取文件长度(字节数)
  • lastModified() 获取最后一次修改时间
  • String [] list()获取目录下所有文件和文件夹的名称数组,返回String数组
  • File[] listFiles()获取指定目录下的所有文件夹和文件目录File数组
        //获取绝对路径
        System.out.println(file.getAbsolutePath());
        //获取绝对路径表示的文件
        System.out.println(file.getAbsoluteFile());
        //获取路径
        System.out.println(file.getPath());
        //获取上一层文件目录路径,若无返回null
        System.out.println(file.getParent());
        //获取文件长度(字节数),不能获取目录的大小
        System.out.println(file.length());
        //获取最后一次修改时间
        System.out.println(file.lastModified());
        //获取目录下所有文件和文件夹的名称数组,返回String数组
        String []filenames=file3.list();
        for (String o:filenames)
        {
            System.out.println(o);
        }
        //获取指定目录下的所有文件夹和文件目录File数组
        File [] filenames2=file3.listFiles();
        for (File files : filenames2)
        {
            System.out.println(files.getName());
        }

1.2 File类的重命名与创建文件功能

renameTo()把文件重命名为指定的文件路径

file2.renameTo(new File("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\suanfa\\binarytree\\123.txt"));

createNewFile() 创建文件,若文件存在,则不创建,返回false
mkdir() 创建文件目录,如果此文件存在,就不创建,如果上级目录不存在也不创建
mkdirs() 创建文件目录,上级目录不存在也会创建

        //创建文件,若文件存在,则不创建,返回false
        file1.createNewFile();
        //创建文件目录,如果此文件存在,就不创建,如果上级目录不存在也不创建
        file4.mkdir();
        //创建文件目录,上级目录不存在也会创建
        file4.mkdirs();

2.Java IO流

2.1 Java IO流的概念

Java程序中输入与输出都是以流的方式的进行,I/O技术是用于处理设备之间的数据传输。在java中把不同的输入/输出源(键盘,文件,网络连接等)抽象表述为“流”(stream)。通过流的形式允许java程序使用相同的方式来访问不同的输入/输出源。stram是从起源(source)到接收的(sink)的有序数据。
主要的IO流

数据单位 字节流 字符流
抽象基类 InputStream OutputStream Reader Writer
节点流 FileInputStream FileOutputStream FileReader FileWriter
处理流 BufferedInputStream BufferedOutputStream(数据流、对象流、打印流等) BufferedReader BufferedWriter

2.2 节点流

Java重要的节点流有FileInputStream FileOutputStream(字节流)和FileReader FileWriter(字符流)
注意:字符流是对字节流进行封装,字符流的底层也是字节流,进行封装转化,更方便简单处理字符文档(可以用记事本打开的)
例子:使用FileInputStream FileOutputStream(字节流)进行文件复制

  • 第一步:创建流 输入流输出流分别指向
  • 第二步:操作流 创建一个中转站(字节数组),在使用输入流read方法将字节流读入数组,直到文件复制完成。
  • 第三步:关闭流
    需要使用try--catch--finally捕获异常
/***
 * 使用FileInputStream和FileOutputStream实现文件复制
 */
public class TestFileStream {
    public static void main(String[] args) {
        //1.创建流
        FileInputStream fis=null;
        FileOutputStream fos=null;
        try{
            fis = new FileInputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\123.txt");
            fos = new FileOutputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\12345.txt");
            //2.使用流
            //2.1使用一个中转站
            byte [] buf=new byte[1024];
            int len;//记录每次读取字节长度
            while((len=fis.read(buf))>=0)
            {
                fos.write(buf,0,len);//将读取的字节,写入新的文件中

            }
        }catch(Exception e)
        {
            e.printStackTrace();
        }finally {
            //3.关闭流
            if(fis!=null)
            {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos!=null)
            {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

例子:使用FileReader FileWriter(字符流)进行txt文档的复制
注意:字符流只能复制字符文档,如果要复制视频、音频、图片等需要使用字节流,字符流复制跟字节流流程一样,就是中转站采用的是字符数组。

  • 第一步:创建流 输入流输出流分别指向
  • 第二步:操作流 创建一个中转站(字符数组),在使用输入流read方法将字符流读入数组,直到文件复制完成。
  • 第三步:关闭流
    需要使用try--catch--finally捕获异常
/***
 * 使用FileReader和FileWriter实现文件复制
 */
public class TestFileReader {
    public static void main(String[] args) {
        FileReader fr=null;
        FileWriter fw=null;

        try {
            //创建流
            fr = new FileReader("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\123.txt");
            fw = new FileWriter("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\12345.txt");
            fw = new FileWriter("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\12345.txt",true);//每次在后面追加,不覆盖
            //使用流
            char []buf=new char[1024];
            int n;
            while((n=fr.read(buf))>=0)
            {
                fw.write(buf,0,n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                if(fr!=null)
                {
                    fr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(fw!=null)
                {
                    fw.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

2.2 缓冲流

作用:缓冲流分为缓存字节流和缓存字符流,目的是提高访问速度,提高便捷。
原理:分别开辟一个输入流缓冲区,和输出流缓冲区,不用每次读取写入都直接操作硬盘,中转站会先从缓冲区读取或写入数据,如果缓冲区没有或者缓存写满,这时缓冲区才会操作硬盘,大大减少操作硬盘次数,节约时间。

注意

  • 缓冲流BufferedInputStream BufferedOutputStream 和 BufferedReader BufferedWriter是高层流,资源回收时,只需要关闭高层流,低层流会自动的关闭。
  • 何时缓冲区写入硬盘,三种情况:缓冲区满、关闭缓冲流、手动使用flush函数。

例子1:使用FileInputStream FileOutputStream(字节流)进行文件复制,并使用BufferedInputStream BufferedOutputStream缓冲流提高速度。

/**
 * 使用缓冲流Buffered来加快文件复制的过程
 */
public class TestBufferedStream {
    public static void main(String[] args) {
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            bis=new BufferedInputStream(new FileInputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\2007.07481.pdf"));
            bos=new BufferedOutputStream(new FileOutputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\2007.pdf"));
            byte [] buf=new byte[1024];
            int n;
            while((n=bis.read(buf))!=-1)
            {
                bos.write(buf,0,n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {//关闭流
            if(bis!=null)
            {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos!=null)
            {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

例子2:使用 BufferedReader BufferedWriter(字符流)进行字符文档复制,要求一行一行的复制

/**
 * 使用缓冲流字符流逐行读取文档,并复制到另一个文档上
 */
public class TestBufferedReader {
    public static void main(String[] args) {
        BufferedReader bor=null;
        BufferedWriter bow=null;
        try {
            //创建流
            bor=new BufferedReader(new FileReader("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\123.txt"));
            bow=new BufferedWriter(new FileWriter("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\12345.txt"));
            //使用流
            String s;
            while((s=bor.readLine())!=null)//如果读不到数据,返回null
            {
                bow.write(s);//写入数据
                bow.newLine();//换行
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                if(bor!=null)
                {
                    bor.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(bow!=null)
                {
                    bow.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }

2.3 其他流

数据流 DataInputStream和DataOutputStream

方便操作各种数据类型,可以将各种数据类型,写入文件,读取出来也能还原出各种数据类型

public class TestDataInputStream {
    public static void main(String[] args) {
        DataInputStream dain=null;
        DataOutputStream daou=null;
        try{
            //创建数据流
            dain=new DataInputStream(new FileInputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\Data.txt"));
            daou=new DataOutputStream(new FileOutputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\Data.txt"));
            daou.writeBoolean(true);
            daou.writeChar('伟');
            daou.writeInt(12);
            daou.writeUTF("hhhhhhh");
            //读取数据
            System.out.println(dain.readBoolean());
            System.out.println(dain.readChar());
            System.out.println(dain.readInt());
            System.out.println(dain.readUTF());

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

        }
    }
}

对象流 ObjectInputStream和ObjectOutputStream

注意
使用对象流写入和读取对象时,需要将类继承Serialization(序列化)或者DeSerialization(反序列化)
对象(内存)---->字节数组(外存,网络)---->(对象)内存

  • static 修饰不参加序列化,可以使用transient使类的变量属性不参加序列化
  • 序列化后不能修改类的内容(除非在创建类的时候,生成类的序列号)
  • 如果对象写入文件,不仅要保证对象序列化,也要保证对象成员变量序列化
public class TestObjectInputStream {
    public static void main(String[] args) {
        ObjectInputStream dain=null;
        ObjectOutputStream daou=null;
        try{
            //创建数据流
            daou=new ObjectOutputStream(new FileOutputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\Data.txt"));
            dain=new ObjectInputStream(new FileInputStream("C:\\Users\\cw\\Desktop\\Project\\Java\\study\\src\\com\\cwstd\\iostream\\Data.txt"));
            daou.writeBoolean(true);
            daou.writeChar('伟');
            daou.writeInt(12);
            daou.writeUTF("hhhhhhh");
            daou.writeObject(new Person(0,"cwstd",22));

            //读取数据
            System.out.println(dain.readBoolean());
            System.out.println(dain.readChar());
            System.out.println(dain.readInt());
            System.out.println(dain.readUTF());
            System.out.println(dain.readObject().toString());

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

        }
    }
}



这篇关于Java IO流的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程