Java io流 之FileOutputStream与FileInputStream 详解

FileOutputStream

文件输出流

方法代码详解:

public class Demo01 {
    public static void main(String[] args)  {
//      fun1();
//      fun2();
        /*
         * 异常处理
         * io 发生异常 都需要停止程序 修改代码
         */
        File file = new File("/Users/james/Desktop/level/123.txt");
        // 增加作用域
        FileOutputStream oStream  = null;
        try {
            // 创建一个流
            // 只要手动创建的流 就需要手动关闭
            oStream = new FileOutputStream(file);
            oStream.write("Hello".getBytes());
        } catch (FileNotFoundException e) {
            // 抛出运行时异常(直接停止程序)
            throw new RuntimeException("文件找不到");
        } catch (IOException e) {
            // 文件编写失败
            throw new RuntimeException("文件无法编写");
        }finally {
            try {
                // 非空判断
                // 如果是空的 说明 流创建失败 就不需要关闭
                if (oStream != null) {
                    oStream.close();
                }               
            } catch (IOException e) {
                // 关闭资源失败 停止程序
                throw new RuntimeException("流无法关闭");
            }
        }   
    }

    /**
     * @throws FileNotFoundException
     * @throws IOException
     * 文件的续写 和 换行
     */
    public static void fun2() throws FileNotFoundException, IOException {
        File file = new File("/Users/james/Desktop/level/123.txt");
        FileOutputStream oStream = new FileOutputStream(file, true);
        oStream.write("Hello\n".getBytes());
        oStream.close();
    }

    /**
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void fun1() throws FileNotFoundException, IOException {
        /*
         * 构造方法需要文件(被写入的文件) 和 文件的路径(被写入的路径)
         * 写入文件流程
         *   1. 绑定要写入的文件 或 文件路径
         *   2. 使用write方法 直接写入
         *   3. 关闭资源
         * 
         */
        // 绑定数据的目的地(绑定要写入的文件)
        // 该路径下 没有该文件 会帮你创建出这个文件
        // 如果有该文件 文件会被覆盖
        File file = new File("/Users/james/Desktop/level/123.txt");

        FileOutputStream oStream = new FileOutputStream(file);
        // 按ascii 表的值输入的
        oStream.write(97);
        byte[] b = {90,100,110};
        oStream.write(b);

        oStream.write(b, 1, 2);
        // 简单写法
        oStream.write("hello".getBytes());      
        oStream.close();
    }
}

FileInputStream

从文件系统中的某个文件中获得输入字节

方法代码示例:

/*
 * 字节输入流
 * inputStream 所有输入流的父类
 * 注意: 字节流 写入的时候 是一个字节一个字节的写 读取是一个字节一个字节的读
 * 
 * 读取文件流程
 * 1.绑定数据源文件(要读哪个文件)
 * 2.使用read方法读
 * 3.关闭资源
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        File file = new File("/Users/james/Desktop/level/134.txt");
        FileInputStream iStream = new FileInputStream(file);
//      fun1(iStream);
//      fun2(iStream);
        int length = (int) file.length();
        byte[] bs = new byte[length];
        while ((iStream.read(bs)) != -1) {
            for (byte b : bs) {
                System.out.println(b);
            }
        }   
        iStream.close();
    }

    /**
     * @param iStream
     * @throws IOException
     */
    public static void fun2(FileInputStream iStream) throws IOException {
        // 循环读取
        // read 方法 每调用一次就 读取一个字节
        // 循环的时候 read方法只能出现一次
        // 声明一个变量保存 读出来的结果
        int read = 0;
        while ((read = iStream.read())!= -1 ) {
            System.out.println(read);
        }
    }
}

输入输出流例题应用:

/*
 * 使用字节的输入输出流进行文件的复制
 * (字节流不但可以写文本 还可以写图片 音频 视频)
 */

public class Demo01 {
    public static void main(String[] args) {
        // 获取系统时间
        long start = System.currentTimeMillis();
        // 异常处理 复制文件
        // 读
        FileInputStream fis = null;
        // 写
        FileOutputStream fos = null;
        try {
        // 复制图片
            fis = new FileInputStream("/Users/james/Desktop/level/图1.jpg");
            fos = new FileOutputStream("/Users/james/Desktop/图2.jpg");

            // 利用缓冲数组读写 效率较高!

            // 开始读 读一个字节 写一个字节
//          int len = 0;
//          while ((len = fis.read()) != -1) {
//              // 直接把读出来的写进文件
//              fos.write(len);
//          }
            // 用字节数组方式读写
            byte[] bs = new byte[1024];
            int len = 0;
            while ((len = fis.read(bs)) != -1) {
                fos.write(bs, 0, len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件找不到!");
        } catch (IOException e) {
            throw new RuntimeException("文件复制失败");
        }finally {
            // 这时读写都完事 可以不用顺序关闭
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("关闭资源失败");
            }finally {
                // 写在一起 如果第一个报异常 第二个流 无法关闭
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException("关闭资源失败");
                }
            }
        }
        long stop = System.currentTimeMillis();
        System.out.println(stop - start);
    }
}

复制一个文件夹里的所有txt到另一个文件内

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

        File oldfile = new File("/Users/james/Desktop/level");
        File newfile = new File("/Users/james/Desktop/xTest");
        copyFileTxt(oldfile, newfile);
    }

    public static void copyFileTxt(File src, File dest) throws IOException {
        File[] listFiles = src.listFiles(new FileTxt());
        for (File file : listFiles) {
            if (file.isFile()) {
                // 读写
                FileInputStream fis = new FileInputStream(file);
                File tempFile = new File(dest, file.getName());
                FileOutputStream fos = new FileOutputStream(tempFile);

                int len = 0;
                byte[] b = new byte[1024];
                while ((len = fis.read(b)) != -1) {
                    fos.write(b, 0, len);
                }
                fis.close();
                fos.close();

            }else {
                copyFileTxt(file, dest);
            }
        }
    }

}

class FileTxt implements FileFilter{

    @Override
    public boolean accept(File pathname) {
        // 文件不被过滤
        if (pathname.isDirectory()) {
            return true;
        }
        // 过滤不是txt的
        String name = pathname.getName();
        return name.endsWith("txt");    
    }   
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值