Java基础:IO实例

一、概念详解

1.定义

    JavaIO流是既可以从中读取,也可以写入到其中的数据流。正如这个系列教程之前提到过的,流通常会与数据源、数据流向目的地相关联,比如文件、网络等等。

2.具体类型

 

二、实现实例

1.读取文件

    /**
     * 1.读取文件
     * @param sourceFilepath 文件全路径,例如:"E:\\sharedfolder\\share.txt";
     */
    public static void ReadFile(String sourceFilepath){
        //1、建立连接
        File file = new File(sourceFilepath);
        InputStream is = null;
        BufferedInputStream bis=null;

//        BufferedWriter(new FileWriter("d:\\c.txt"));

        try {
            //2、选择流(此处为输入流)
            is = new FileInputStream(file);
            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输入效率,建议!
//            bis = new BufferedInputStream(new FileInputStream(file));
            bis=new BufferedInputStream(is);
            int len = 0;
            //3、操作:以每次1024大小读取
            byte[] buff = new byte[1024];
            while((len = bis.read(buff))!= -1) {
                String ss = new String(buff,0,len);    // 将byte类型的数组转化成字符串,方便下面输出
                System.out.println(ss);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件失败!");
        }finally {
            if (is != null) {    //若is还存在就需要释放,否则不需要释放
                try {
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭文件输入流失败");
                }
            }
        }
    }

2.写入文件

    /**
     * 2.写入文件
     * @param targetFilepath 文件全路径,例如:"E:\\sharedfolder\\share_target.txt";
     */
    public static void WriteFile(String targetFilepath){
        //1、建立连接
        File file = new File(targetFilepath);
        OutputStream os = null;
        BufferedOutputStream bos=null;
        try {
            //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
            os = new FileOutputStream(file,true);
//            //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
            bos = new BufferedOutputStream(new FileOutputStream(file,true));
            String string = "Programmer say : Hello World!";
            byte[] data = string.getBytes();    //将字符串转换为字节数组,从而写出到指定文件

            //3、写入文件
            bos.write(data, 0, data.length);
            bos.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件没有找到!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("写入文件失败!");
        }finally {
            if (os != null) {
                try {
                    bos.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("关闭输出流失败!");
                }
            }
        }
    }


3.拷贝单个文件

    /**
     * 3.复制文件到直指定文件
     * @param sourceFilepath 源文件全路劲:"E:\\sharedfolder\\share.txt"
     * @param targetFilepath 目标文件全路径:"E:\\sharedfolder\\share_copy2.txt"
     */
    public static void copyFile(String sourceFilepath,String targetFilepath){
        //1.检测路径环境
        File srcFile=new File(sourceFilepath);
        File destFile=new File(targetFilepath);
        if(! srcFile.isFile()){ //当不是文件或者为null
            System.out.println("只能拷贝文件");
            try {
                throw new IOException("只能拷贝文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(destFile.isDirectory()){    //不能建立于文件夹同名的文件
            System.out.println(destFile.getAbsolutePath()+"不能建立于文件夹同名的文件");
            try {
                throw new IOException(destFile.getAbsolutePath()+"不能建立于文件夹同名的文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //2、建立连接
        InputStream is =null;
        OutputStream os = null;
        try {
            //3、选择流
            is = new FileInputStream(srcFile);
            os = new FileOutputStream(destFile);
            //4、操作: 循环{读取+写出} + 强制刷新
            byte[] inData = new byte[1024];
            int len = 0;
            while(-1 != (len = is.read(inData))){    //读取文件
                os.write(inData, 0, len);    //每次以inData大小读取数据
            }
            os.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取文件失败!");
        }finally {
            if (os != null)
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (is != null)
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

4.拷贝整个目录

    /**
     * 4.拷贝文件夹
     * @param srcPath 源文件夹:"E:\\sharedfolder"
     * @param destPath 目标文件夹:"E:\\sharedfolder2"
     */
    public static void copyDir(String srcPath,String destPath){
        File src = new File(srcPath);
        File dest = new File(destPath);
        //1、如果是文件夹
        if (src.isDirectory()){
//      Creates a new File instance from a parent pathname string(destPath)
//      and a child pathname string(src.getName()).
            dest = new File(destPath,src.getName());    //在路径destPath中新建一个src.getName()子目录
            dest.mkdirs();    //Creates the directory named by this abstract pathname(dest)
        }
        copyDirDetail(src,dest);
    }

    /**
     * 4.1 拷贝文件夹的细节实现(单独提出需要递归的部分,方便递归)
     * @param src
     * @param dest
     */
    public static void copyDirDetail(File src,File dest){
        //1、如果是文件
        if (src.isFile()) {
            copyFile(src.getAbsolutePath(),dest.getAbsolutePath());
        }else if (src.isDirectory()) {
            //2、如果是文件夹
            dest.mkdirs();    //建立一个新的子目录
            for(File sub:src.listFiles())
                copyDirDetail(sub,new File(dest,sub.getName()));//3、递归查找子孙级
        }
    }

三、参考

1.Java IO流学习总结一:输入输出流

https://blog.csdn.net/zhaoyanjun6/article/details/54292148/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值