• IO流


    我们要想实现IO的操作,就必须要知道硬盘上文件的表现形式。
    而java就提供了一个类File供我们使用
     
    File:文件和目录路径名的抽象表示形式

      1、构造方法:

        File(String pathname):根据一个路径得到File对象
             File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
             File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象

      2、创建功能:

          public boolean createNewFile():     创建文件,只能创建文件, 如果存在这样的文件,就不创建了 , 什么也不返回 ,创建成功返回true
          public boolean mkdir():                   创建文件夹 ,只能创建文件夹,如果存在这样的文件夹,就不创建了 , 返回false 创建成功返回true
          public boolean mkdirs():                 创建文件夹,只能创建文件夹,如果父文件夹不存在,会帮你创建出来,创建成功返回true,如果已经存在,返 回false
          注意:如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。

      3、删除功能:

        public boolean delete()
                Java中的删除不走回收站。
           要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹

      4、重命名功能:

         public boolean renameTo(File dest)
          如果路径名相同,就是改名。
                 如果路径名不同,就是改名并剪切

      5、判断功能:

        public boolean isDirectory():判断是否是目录
          public boolean isFile():判断是否是文件
          public boolean exists():判断是否存在
          public boolean canRead():判断是否可读
          public boolean canWrite():判断是否可写
          public boolean isHidden():判断是否隐藏

      6、获取功能:

        public String getAbsolutePath():获取绝对路径
          public String getPath():获取相对路径
          public String getName():获取名称
          public long length():获取长度。字节数
          public long lastModified():获取最后一次的修改时间,毫秒值

      7、高级获取功能:

        public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
          public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组

          public String[] list(FilenameFilter filter): 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录
          public File[] listFiles(FileFilter filter) : 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录
          public File[] listFiles(FilenameFilter filter) : 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录

    IO流

      IO的分类

       按流向:

        ①、输入流:读取数据

        ②、输出流:写出数据

       按数据类型:

        ①、字节流

          字节输入流:读取字节数据,inPutStream(抽象超类)

          字节输出流:写出字节数据,OutPutStream(抽象超类)

        ②:字符流

          字符输入流:读取字符数据,Reader(抽象超类)

          字符输出流:写出字符数据,Writer(抽象超类)

        注意:每种基类的子类都是以父类名作为后缀名。
         * XxxOutputStream
         * XxxInputStream
         * XxxReader
         * XxxWriter

     1、字节普通流

      1)FileInPutStream 

       ①:构造方法:

         FileInputStream(File file)
              FileInputStream(String name)

       ②:读取数据

         public int read() throws IOException 从此输入流中读取一个数据字节。如果没有输入可用,则此方法将阻塞。下一个数据字节;如果已到达文件末尾,则返回 -1
              public int read(byte[] b) throws IOException 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方 法将阻塞。读入缓冲区的字节总数,如果因为已经 到达文件末尾而没有更多的数据,则返回 -1。
             public int read(byte[] b, int off, int len)  throws IOException  从此输入流中将最多 len 个字节的数据读入一个 byte数组中。如果 len 不为 0,则在输入可用之前,该方法 将阻塞;否则,不读取任何字节并返回 0。

      2)FIleOutPutStream

       ①:构造方法

        FileOutputStream(File file)
        FileOutputStream(String name)

       ②:字节输出流操作步骤:
        a:创建字节输出流对象
        b:调用write方法写数据
           c:释放资源

       ③:写出数据

        public void write(int b):写一个字节
          public void write(byte[] b):写一个字节数组
          public void write(byte[] b,int off,int len):写一个字节数组的一部分

       ④:如何实现写入数据的换行:
        windows:\r\n
        linux:\n
        Mac:\r

       ⑤:如何实现数据的追加写入?

        public FileOutputStream(File file, boolean append) throws FileNotFoundException,用此构造且第二个参数是true

    2、字节缓冲流

      通过定义数组的方式确实比以前一次读取一个字节的方式快很多,所以,看来有一个缓冲区还是非常好的。 既然是这样的话,那么,java开始在设计的时候,它也考虑到了这个问题,就专门提供了带缓冲区的字节类

      字节缓冲输入流:BufferedFileInPutStream
      字节缓冲输出流:BufferedFileOutPutStream

      构造方法可以指定缓冲区的大小,但是我们一般用不上,因为默认缓冲区大小就足够了

      为什么不传递一个具体的文件或者文件路径,而是传递一个OutputStream对象呢?

        原因很简单,字节缓冲区流仅仅提供缓冲区,为高效而设计的。但是呢,真正的读写操作还得靠基本的流对象实现

      字节流复制文件的四种方式

    查看代码
    import java.io.*;
    
    /**
     * 四种文件复制方式的比较
     * 1.普通字节流一次读写一个字节 共耗时:138983毫秒
     * 2.普通字节流一次读写一个字节数组 共耗时:228毫秒
     * 3.字节缓冲流一次读写一个字节 共耗时:897毫秒
     * 4.字节缓冲流一次读写一个字节数组 共耗时:78毫秒
     * Created by Yang on 2017/5/31.
     */
    public class CopyFileTest {
        public static void main(String[] args) {
            String srcFile="F:\\ChromeDownload\\video\\钟无艳-谢安琪.mp3";
            String destFile="钟无艳-谢安琪.mp3";
            //开始时间
            long start=System.currentTimeMillis();
            method4(srcFile,destFile);
            //结束时间
            long end=System.currentTimeMillis();
            System.out.println("共耗时:"+(end-start)+"毫秒");
        }
        //1.普通字节流一次读写一个字节
        public static void method1(String srcFile,String destFile){
            InputStream fis = null;
            OutputStream fos = null;
            try {
                fis = new FileInputStream(srcFile);
                fos = new FileOutputStream(destFile);
                int i = 0;
                while ((i = fis.read()) != -1) {
                    fos.write(i);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源,先关谁都行
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //2.普通字节流一次读写一个字节数组
        public static void method2(String srcFile,String destFile){
            InputStream fis = null;
            OutputStream fos = null;
            try {
                fis = new FileInputStream(srcFile);
                fos = new FileOutputStream(destFile);
                byte[] bys=new byte[1024];
                int len = 0;
                while ((len = fis.read(bys)) != -1) {
                    fos.write(bys,0,len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源,先关谁都行
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //3.字节缓冲流一次读写一个字节
        public static void method3(String srcFile,String destFile){
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(srcFile));
                bos = new BufferedOutputStream(new FileOutputStream(destFile));
                int i = 0;
                while ((i = bis.read()) != -1) {
                    bos.write(i);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源,先关谁都行
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //4.字节缓冲流一次读写一个字节数组
        public static void method4(String srcFile,String destFile){
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(srcFile));
                bos = new BufferedOutputStream(new FileOutputStream(destFile));
                byte[] bys=new byte[1024];
                int len = 0;
                while ((len = bis.read(bys)) != -1) {
                    bos.write(bys,0,len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //释放资源,先关谁都行
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

     3、转换流

      由于字节流操作中文不是特别方便,所以,java就提供了转换流,将字节流转换为字符流
           字符流=字节流+编码表。


      1)编码表
           由字符及其对应的数值组成的一张表
       常见编码表
           ASCII/Unicode 字符集
           ISO-8859-1
           GB2312/GBK/GB18030
           BIG5
           UTF-8

       编码:

        把看得懂的变成看不懂的 String-- byte[]
        public byte[] getBytes(String charsetName)throws UnsupportedEncodingException 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中

       解码:

        把看不懂的变成看得懂的 byte[]--String

        public String(byte[] bytes,String charsetName)throws UnsupportedEncodingException  通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。新 String 的长度是字符集的函数,因此可能不等于 byte 数组的长度

       编码问题其实很简单,只要编码的格式和解码的格式是一致的就不会有任何问题

        
      2)InPutStreamReader:转换输入流
            构造方法:
        public InputStreamReader(InputStream in)创建一个使用默认字符集的 InputStreamReader。
        public InputStreamReader(InputStream in,String charsetName) throws UnsupportedEncodingException创建使用指定字符集的 InputStreamReader。
       成员方法:
        public int read() throws IOException读取单个字符。
        public int read(char[] cbuf)   throws IOException将字符读入数组。在某个输入可用、发生 I/O 错误或者已到达流的末尾前,此方法一直阻塞。
        public int read(char[] cbuf,
                              int offset,
                              int length)
                              throws IOException将字符读入数组中的某一部分。

      3)OutPutStreamWriter:转换输出流

       构造方法:
        public OutputStreamWriter(OutputStream out)创建使用默认字符编码的 OutputStreamWriter 将字节流数据转换为字符流。
        public OutputStreamWriter(OutputStream out,String charsetName)throws UnsupportedEncodingException创建使用指定字符集的 OutputStreamWriter 将字节流数据转换为字符流。
       成员5种写入方法:
             public void write(int c)throws IOException写入单个字符。
             public void write(char[] cbuf)throws IOException写入字符数组。
             public abstract void write(char[] cbuf,int off,int len)throws IOException写入字符数组的某一部分。
             public void write(String str)throws IOException写入字符串。
             public void write(String str,int off,int len)throws IOException写入字符串的某一部分

      转换流的名字比较长,而我们常见的操作都是按照本地默认编码实现的,所以,为了简化我们的书写,转换流提供了对应的子类
           FileWriter
           FileReader

     4、字符普通流

      1)FileReader  

        继承自InPutStreamReader用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。要自己指定这些值,可以先在 FileInputStream 上构造一个 InputStreamReader

        构造方法:
          public FileReader(File file) throws FileNotFoundException在给定从中读取数据的 File 的情况下创建一个新 FileReader。
          public FileReader(String fileName) throws FileNotFoundException在给定从中读取数据的文件名的情况下创建一个新 FileRea

      2)FileWriter

         继承自OutputStreamWriter,用来写入字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是可接受的。要自己指定这些值,可以先在 FileOutputStream 上构造一个 OutputStreamWriter

        构造方法:
          public FileWriter(File file)throws IOException根据给定的 File 对象构造一个 FileWriter 对象。
          public FileWriter(File file,boolean append) throws IOException根据给定的 File 对象构造一个 FileWriter 对象。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。
          public FileWriter(String fileName) throws IOException根据给定的文件名构造一个 FileWriter 对象。
          public FileWriter(String fileName,boolean append) throws IOException根据给定的文件名以及指示是否附加写入数据的 boolean 值来构造 FileWriter 对象

     5、字符缓冲流

      1)BufferedReader

        public class BufferedReader extends Reader从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值就足够大了 

       构造方法:
        public BufferedReader(Reader in)创建一个使用默认大小输入缓冲区的缓冲字符输入流。 
        public BufferedReader(Reader in,int sz)创建一个使用指定大小输入缓冲区的缓冲字符输入流。 

       成员方法:
        public String readLine() throws IOException读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。

       返回:
        包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
       抛出:
        IOException - 如果发生 I/O 错误

    br=new BufferedReader(new FileReader("a.txt"));
    //一次读取一行
    String line=null;
    while((line=br.readLine())!=null){
        System.out.println(line);
    }

      2)BufferedWriter

        public class BufferedWriter extends Writer将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了

        该类提供了 newLine() 方法,它使用平台自己的行分隔符概念,此概念由系统属性 line.separator 定义。并非所有平台都使用新行符 ('\n') 来终止各行。因此调用此方法来终止每个输出行要优于直接写入新行符

       构造方法:
        public BufferedWriter(Writer out)创建一个使用默认大小输出缓冲区的缓冲字符输出流。 
        public BufferedWriter(Writer out,int sz)创建一个使用给定大小输出缓冲区的新缓冲字符输出流。

       成员方法:
        public void newLine() throws IOException写入一个行分隔符。行分隔符字符串由系统属性 line.separator 定义,并且不一定是单个新行 ('\n') 符。 根据系统不同,自动分配换行符。

    bw=new BufferedWriter(new FileWriter("bw.txt",true));
    for (int i = 0; i <10 ; i++) {
        bw.write("hello"+i);
        bw.newLine();
    }
    bw.flush();

      

      字符流复制文件的五种方式

    查看代码
    
    /**
     *  1.普通字符流一次读写一个字符
     *  2.普通字符流一次读写一个字符数组
     *  3.字符缓冲流一次读写一个字符
     *  4.字符缓冲流一次读写一个字符数组
     *  5.字符缓冲流一次读写一行文本
     *  Created by Yang on 2017/6/2.
     */
    public class CopyFileTest7 {
        public static void main(String[] args) {
            String srcFile="a.txt";
            String destFile="b.txt";
    //        method1(srcFile,destFile);//1.普通字符流一次读写一个字符
    //         method2(srcFile,destFile);//2.普通字符流一次读写一个字符数组
    //        method3(srcFile,destFile); //3.字符缓冲流一次读写一个字符
    //        method4(srcFile,destFile); //4.字符缓冲流一次读写一个字符数组
            method5(srcFile,destFile);  //5.字符缓冲流一次读写一行文本
        }
        //1.普通字符流一次读写一个字符
        public static void method1(String srcFile,String destFile){
            FileReader fr=null;
            FileWriter fw=null;
            try {
                fr=new FileReader(srcFile);
                fw=new FileWriter(destFile);
                int i=0;
                while((i=fr.read())!=-1){
                    fw.write(i);
                }
            } 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();
                    }
                }
            }
        }
        //2.普通字符流一次读写一个字符数组
        public static void method2(String srcFile,String destFile){
            FileReader fr=null;
            FileWriter fw=null;
            try {
                fr=new FileReader(srcFile);
                fw=new FileWriter(destFile);
                char[] chars=new char[1024];
                int len=0;
                while((len=fr.read(chars))!=-1){
                    fw.write(chars,0,len);
                }
            } 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();
                    }
                }
            }
        }
        //3.字符缓冲流一次读写一个字符
        public static void method3(String srcFile,String destFile){
            BufferedReader br=null;
            BufferedWriter bw=null;
            try {
                br=new BufferedReader(new FileReader(srcFile));
                bw=new BufferedWriter(new FileWriter(destFile));
                int i=0;
                while((i=br.read())!=-1){
                    bw.write(i);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(bw!=null){
                    try {
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //4.字符缓冲流一次读写一个字符数组
        public static void method4(String srcFile,String destFile){
            BufferedReader br=null;
            BufferedWriter bw=null;
            try {
                br=new BufferedReader(new FileReader(srcFile));
                bw=new BufferedWriter(new FileWriter(destFile));
                char[] chars=new char[1024];
                int len=0;
                while((len=br.read(chars))!=-1){
                    bw.write(chars,0,len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(bw!=null){
                    try {
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        //5.字符缓冲流一次读写一行文本(推荐掌握)
        public static void method5(String srcFile,String destFile){
            BufferedReader br=null;
            BufferedWriter bw=null;
            try {
                br=new BufferedReader(new FileReader(srcFile));
                bw=new BufferedWriter(new FileWriter(destFile));
                //一次读写一行文本
                String line=null;
                while((line=br.readLine())!=null){
                    bw.write(line);
                    bw.newLine();
                    bw.flush();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(br!=null){
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(bw!=null){
                    try {
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

     6、随机访问流:RandomAccessFile

      RandomAccessFile类并不属于流,是Object类的子类,但它融合了InPutStream和OutPutStream的功能,支持浏览器的随机访问读取和写入。

      构造方法:
        1.public RandomAccessFile(String name,String mode);
             第一个参数是文件路径,第二个参数是操作文件的模式。模式一共有四种,最常用的是 "rw",这种方式表示既可以对文件读取数据,也能写数据。
        2.public RandomAccessFile(File file,String mode)

      

      此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte 数组。存在指向该隐含数组的光标或索引,称为文件指针;输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针。写入隐含数组的当前末尾之后的输出操作导致该数组扩展。该文件指针可以通过 getFilePointer 方法读取,并通过 seek 方法设置。

       public long getFilePointer() throws IOException 返回此文件中的当前偏移量。 
       public void seek(long pos) throws IOException 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作。偏移量的设置可能会超出文件末尾。偏移量的设置超出文件末尾不会改变文件的长度。只有在偏移量的设置超出文件末尾的情况下对文件进行写入才会更改其长度。

    附录:

    // 填写网络流地址。
    InputStream inputStream = new URL("https://www.ksyun.com").openStream();

    END.

  • 相关阅读:
    oracle归档日志增长过快处理方法
    Oracle“死锁”模拟
    Oracle 手工清除回滚段的几种方法
    Oracle 一次 锁表 处理小记
    Oracle中如何判断一个字符串是否含有汉字
    机房收费系统验收总结
    hdu 4747 Mex (线段树)
    Java 5 的新标准语法和用法详解集锦
    java类加载器行为[笔记]
    poj1330Nearest Common Ancestors(LCA小结)
  • 原文地址:https://www.cnblogs.com/yangyongjie/p/16338010.html
Copyright © 2020-2023  润新知