zoukankan      html  css  js  c++  java
  • 【Java的IO流之文件字节输入输出流 24】

    一、文件通常是由一连串的字节或者字符构成,组成文件的字节序列称为字节流,组成文件的字符列称为字符流

    Java中可根据流的方向可分为输入流和输出流

    输入流是将文件或其他输入设备的数据加载到内存的过程(数据转换成ASSIC码)

    输出流恰恰相反,是将内存中的数据保存到文件或其他输出设备

    二、Java.IO常用流

    字节流:

    FIleInputStream

    FileOuputStream

    字符流:

    FileReader

    FileWriter

    包装流:

    BufferedReader

    BufferedWriter

    转换流:

    InputStreamReader

    OuputStreamReader

    打印流:

    PrintStream

    PrintWriter

    对象流:

    ObjectInputStream

    ObjectOuputStream

    文件类:

    java.io.File

    三、文件字节输入流:FileInputStream:从文件系统中的某个文件中获得输入字节。用于读取诸如图像数据之类的原始字节流,要读取字节流,请考虑FileReader

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/28 14:22
     * FileInputStream  --> 构造方法:FileInputStream(String name)(name指文件的路径)
     * -->int read()方法:读取文件内的一个数据字节
     */
    public class FileInputStreamTest01 {
        public static void main(String[] args){
            FileInputStream file = null;
    
            try {
                file = new FileInputStream("/Users/wufq/Desktop/test.txt");
    
                int i1 = file.read();
                System.out.println(i1);//97
    
                int i2 = file.read();
                System.out.println(i2);//98
    
                int i3 = file.read();
                System.out.println(i3);//99
    
                int i4 = file.read();
                System.out.println(i4);//100
    
                int i5 = file.read();
                System.out.println(i5);//-1 -->read没有读取到文件数据时返回-1
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //为了保证流的关闭
                if(file !=null){
                    try {
                        file.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }

    上面程序读取文件数据比较繁琐,多次写read,下面是利用循环来读取

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/28 14:44
     */
    public class FileInputStreamTest02 {
        public static void main(String[] args){
            FileInputStream file1 = null;
    
            try {
                file1 = new FileInputStream("/Users/wufq/Desktop/test.txt");
    
                int temp = 0;
                while ((temp=file1.read())!= -1){
                    System.out.println(temp);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(file1!=null){
                    try {
                        file1.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }
    ====执行结果====
    97
    98
    99
    100

    2、一次读取多个字节

    一种常用的读取文件的方式,

    使用“int read();”方法读取硬盘访问次数太频繁。

    效率低,伤硬盘

    使用“int read(byte[] bytes)”:

    读取:一次读取多个字节。该方法执行结束之后返回值是该次读取到的字节数。读取不到返回-1

    返回:读入缓冲区的字节总数,如果文件末尾没有数据可读则返回-1

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/28 15:05
     * read(byte[] bytes)  -->一次可以读取多个数据
     */
    public class FileInputStreamTest03 {
        public static void main(String[] args){
    
            FileInputStream fis = null;
    
            try {
                //创建文件字节输入流
                fis = new FileInputStream("/Users/wufq/Desktop/test.txt");
                //开始读
                byte[] bs = new byte[4];//一次只能读取4个字节
                int countRead = fis.read(bs);// int read(byte[] bytes) -->返回读入缓冲区的字节总数,如果文件末尾没有数据则返回-1
    
                //把读取文件内的数据已字符串的形式输出
                String str = new String(bs,0,countRead);
                System.out.println(str);
    
                countRead = fis.read(bs); // -->test文件内是6个数,而bs数组只存放了4个字节,
                // 所以第一次读取文件放到缓冲池里面的只有4个数,第二次读取文件放到缓存池只有两个字节
                String str1 = new String(bs,0,countRead);
                System.out.println(str1);
    
                //读取不到返回-1
                countRead = fis.read(bs);
                String str2 = new String(bs,0,countRead);
                System.out.println(str2);
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fis!= null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
    }

    利用循环来控制读取数据

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/28 17:35
     */
    public class FileInputStreamTest04 {
        public static void main(String[] args){
            FileInputStream fis = null;
    
            try {
                //创建文件字节输入流
                fis = new FileInputStream("/Users/wufq/Desktop/test.txt");
                //定义数组,用于存放一次可以读取多个数据的字节数
                byte[] bytes = new byte[4];
                //初始化字节总数 --->开始读取,读取后返回缓冲池内的字节总数
                int countRead = 0;
    
                //循环控制返回读取文件内的字节总数,直到不能读取不到(-1)停止
                while ((countRead = fis.read(bytes))!=-1){
                    //把数组中的元素转换成字符串
                    String string = new String(bytes,0,countRead);
                    System.out.println(string);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if(fis !=null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    ====执行结果====
            abcd
            ef

    四、文件字节输出流:FileOuputStream:将数据写入文件内

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/29 11:47
     */
    public class FileOuputStreamTest01 {
        public static void main(String[] args){
            FileOutputStream fos = null;
            try {
                //创建输出流
                fos= new FileOutputStream("/Users/wufq/Desktop/test.txt");//先将文件内的数据全部清除,然后写入新的数据
                fos = new FileOutputStream("/Users/wufq/Desktop/test.txt",true);//不清除文件内的数据,写入的数据在原数据后追加
    
                //需要写入的数据
                String msg ="linux";
                //将msg字符编码为byte序列,并将结果存储到byte数组内
                byte[] bytes = msg.getBytes();
    
                fos.write(bytes);//将数组内的数据全部写入文件
                fos.write(bytes,2,2);//write(arr,int off,int len):arr代表数组,off代表偏移量,len代表长度。
                // 整体意思:将bytes数组内偏移量为2,长度为2的数据写入文件-->即:把nu写入文件内
    
                //手动刷新保证所有数据全部写入文件
                fos.flush();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }

    五、练习题

    1、把A文件内的数据复制到B文件内(并且不能覆盖掉B文件内的原有数据)

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/29 14:06
     * 需求:从一个文件内读取数据,写入到另外一个文件内
     */
    public class FileInOuputStream01 {
        public static void main(String[] args){
            FileInputStream fis = null;
            FileOutputStream fos = null;
    
            try {
                fis = new FileInputStream("/Users/wufq/Desktop/copy.txt");
                fos = new FileOutputStream("/Users/wufq/Desktop/paste.txt",true);
    
                byte[] bytes = new byte[4];
                while ((fis.read(bytes))!= -1){
                        String msg = new String(bytes);
                        byte[] bytes1 = msg.getBytes();
                        fos.write(bytes1);
                }
                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            } finally {
                if(fis!=null&fos!=null){
                    try {
                        fis.close();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
            }
        }
    }
    ====执行结果====
    copy的文件内容:testAAAA
    paste的文件内容:AAA
    执行后:
    paste由AAA--->AAAtestAAAA

    2、把c盘下的图片拷贝到D盘

    package com.JavaStudy.studyIo0628;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /**
     * @Author wufq
     * @Date 2020/6/29 14:50
     * 把c盘下的图片拷贝到D盘
     */
    public class FileInOuputSteam02 {
        public static void main(String[] args){
            FileInputStream fis = null;
            FileOutputStream fos = null;
    
            try {
                fis = new FileInputStream("/Users/wufq/Desktop/11.jpg");
                fos = new FileOutputStream("/Users/wufq/Desktop/bank/11.jpg");
    
                byte[] b1 = new byte[1024];
                while ((fis.read(b1))!=-1){
                    fos.write(b1);
                }
                fos.flush();
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            } finally {
                if(fis!=null&fos!=null){
                    try {
                  //谁先定义后关闭谁
                        fos.close();
                fis.close(); }
    catch (IOException e) { e.printStackTrace(); } } } } }

    两则的区别:

    读写文件:读取文本内容时,需要把读取到的字节数转换为字符,然后在把字符写入到文件内

    读写图片:只需要读取,然后直接写入(不需要转换成字符串)

  • 相关阅读:
    mysql之左连接与右连接
    java使用AES加密解密 AES-128-ECB加密
    hive入门
    hive sequencefile导入文件遇到FAILED: SemanticException Unable to load data to destination table. Error: The file that you are trying to load does not match the file format of the destination table.错误
    hive查询遇到java.io.EOFException: Unexpected end of input stream错误
    hive内部表、外部表、分区
    hive的join查询
    hive的row_number()函数
    hive的UDF读取配置文件
    hive里的group by和distinct
  • 原文地址:https://www.cnblogs.com/frankruby/p/13188173.html
Copyright © 2011-2022 走看看