Java IO流之访问文件的字节输入流FileInputStream和字节输入流FileOutputStream的详解

简介: Java IO流之访问文件的字节输入流FileInputStream和字节输入流FileOutputStream的详解

一、FileInputStream的使用详解如下:

public class FileInputStream_ {
    /**
     * 演示读取文件...
     * 单个字节的读取,效率比较低
     * ->使用read(byte[] b)
     */
    @Test
    public void readFile01() {
        String filePath = "D:\\hello.txt";
        int readData = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            //fileInputStream.read()方法
            //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止
            //如果返回-1,表示读取完毕。
            while ((readData = fileInputStream.read()) != -1) {
                System.out.print((char) readData); //转成char进行显示
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流释放资源
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 使用read(byte[] b)读取文件,提高效率
     */
    @Test
    public void readFile02() {
        String filePath = "D:\\hello.txt";
        int readData = 0;
        //字节数组
        byte[] buf = new byte[8]; //一次读取八个字节
        int readLen = 0;
        FileInputStream fileInputStream = null;
        try {
            //创建FileInputStream对象,用于读取文件
            fileInputStream = new FileInputStream(filePath);
            //fileInputStream.read(byte[] b)方法
            //从该输入流读取最多b.length字节的数据到字节数组中。此方法将阻塞,直到某些输入可用。
            //如果返回-1,表示读取完毕
            //如果读取正常,返回实际读取的字节数。
            //如果最后一次读取的字节数,不够八个,则返回实际的字节数。如果够的话,每次最多只能读取八个
            while ((readLen = fileInputStream.read(buf)) != -1) {
                //把每次读取的字节数,返回给readLen,用字节数组构建一个字符串,显示出来。
                System.out.print(new String(buf, 0, readLen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭文件流释放资源
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、FileOutputStream的使用详解如下:

public class FileOutputStream01 {
    /**
     * 演示使用FileOutputStream将数据写到文件中
     * 如果该文件不存在,则创建该文件
     */
    @Test
    public void writeFile() {
        //创建FileOutputStream对象
        String filePath = "D:\\a.txt";
        FileOutputStream fileOutputStream = null;
        try {
            //1.new FileOutputStream(filePath);创建方式,当写入内容时,会覆盖原来的内容
            //1.new FileOutputStream(filePath,true);创建方式,当写入内容时,是追加到文件后面
            fileOutputStream = new FileOutputStream(filePath,true);
            //写入一个字节
            //fileOutputStream.write('L');
            //写入字符串
            String str = "ly,world";
            //str.getBytes()可以把字符串->字节数组
            //write(byte[] b) 将b.length个字节从指定的字节数组写入此文件输出流。
            //fileOutputStream.write(str.getBytes());
            //write(byte[] b,int off,int len)将len字节从位于偏移量off的指定字节数组写入此文件的输出流
            fileOutputStream.write(str.getBytes(),0,2);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

具体案例如下

一、复制图片

@Test
    public void test2(){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.提供File类的对象
            File file1 = new File("工作二维码.png");
            File file2 = new File("工作二维码3.png");
            //2.造流
            fis = new FileInputStream(file1);
            fos = new FileOutputStream(file2);
            //3.复制图片
            byte[] buffer = new byte[5];
            int len;
            while ((len=fis.read(buffer))!=-1){
              //读取到后,就写入到文件,通过FileOutputStream
              //即:是一边读,一边写
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (fis!=null){
                try {
                    fis.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

二、复制文件

//指定路径下文件的复制
    public void copyFile(String srcPath,String descPath){
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            //1.提供File类的对象
            File file1 = new File(srcPath);
            File file2 = new File(descPath);
            //2.造流
            fis = new FileInputStream(file1);
            fos = new FileOutputStream(file2);
            //3.复制图片
            byte[] buffer = new byte[1024];
            int len;
            while ((len=fis.read(buffer))!=-1){
              //void write(byte[] b ,int off, int len)
              //将byte[]数组下标off开始的len长度的数据写入当前输出流
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (fis!=null){
                try {
                    fis.close();
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Test
    public void testCopyFile(){
        long start = System.currentTimeMillis();
        String srcPath="C:\\Users\\DELL\\Desktop\\1.回顾类-封装和继承.mp4";
        String descPath= "C:\\Users\\DELL\\Desktop\\1.回顾类-封装和继承3.mp4";
        copyFile(srcPath,descPath);
        long end = System.currentTimeMillis();
        System.out.println("复制消耗的时间:"+(end-start));
    }


目录
相关文章
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
500 1
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
481 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
949 0
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
689 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1059 5
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
766 1
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
682 1
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案
Java 数据库 Spring
564 0
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
815 16