文件编程常用方法集锦

目录

目标

方法集锦

把一个文件的内容复制到另一个文件内(2G以内)

把一个文件的内容复制到另一个文件内(文件大小没有限制)

寻找javaFile文件夹同级别的pythonFile文件夹

判断文件是否存在

创建目录(不能创建多级目录)

创建目录(能创建多级目录)

拷贝文件

移动文件

删除文件或文件夹

遍历文件

删除文件夹下所有文件(慎重操作)

拷贝多级文件


目标

掌握JAVA对文件的各种操作。本文是对我以前的一篇文章《java.io.File类常用的方法》的补充。

方法集锦

把一个文件的内容复制到另一个文件内(2G以内)

    /**
     * 把一个文件的内容复制到另一个文件内。(注意:文件不超过2G。)
     * 反复运行该方法目标文件的内容不会被追加。
     */
    public void FileContentCopy() {
        FileChannel from=null;
        FileChannel to=null;
        try {
            //源头文件(读入)
            from = new FileInputStream("C:\\Users\\20203\\Desktop\\网络编程\\a.txt").getChannel();
            //目标文件(写出)
            to = new FileOutputStream("C:\\Users\\20203\\Desktop\\网络编程\\b.txt").getChannel();

            //操作系统出于性能的考虑,会将数据缓存,不是立刻写入磁盘。可以调用 force(true) 方法将文件内容和元数据(文件的权限等信息)立刻写入磁盘
            //to.force(true);
            /**
             * transferTo()方法运用了零拷贝优化。
             * 第一个参数:从第几个字节开始传输。
             * 第二个参数:传输多少个字节,这里我设置为源头文件的字节大小。
             * 第三个参数:目标文件的通道。
             */
            from.transferTo(0, from.size(), to);
        }catch (IOException e){

        }finally {
            try {
                if(from!=null){
                    from.close();
                }
                if(to!=null){
                    to.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }

    }

把一个文件的内容复制到另一个文件内(文件大小没有限制)

    /**
     * 把一个文件的内容复制到另一个文件内。(注意:文件超过2G使用分批传输。)
     * 反复运行该方法目标文件的内容不会被追加。
     */
    public void FileContentCopy2() throws IOException {
        FileChannel from=null;
        FileChannel to=null;
        try {
            //源头文件(读入)
            from = new FileInputStream("C:\\Users\\20203\\Desktop\\网络编程\\a.txt").getChannel();
            //目标文件(写出)
            to = new FileOutputStream("C:\\Users\\20203\\Desktop\\网络编程\\b.txt").getChannel();
            /**
             * transferTo()方法运用了零拷贝优化。
             * 第一个参数:从第几个字节开始传输。
             * 第二个参数:传输多少个字节,这里我设置为源头文件的字节大小。
             * 第三个参数:目标文件的通道。
             */
            long transferCount = from.size();
            while (transferCount > 0) {
                //返回值表示传输了多少数据。
                long l = from.transferTo(from.size() - transferCount, transferCount, to);
                //剩余还有多少数据没有传输。
                transferCount = transferCount - l;
            }
        }catch (IOException e){

        }finally {
            try {
                if(from!=null){
                    from.close();
                }
                if(to!=null){
                    to.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

寻找javaFile文件夹同级别的pythonFile文件夹

    /**
     * 寻找javaFile文件夹同级别的pythonFile文件夹。
     * .当前目录
     * ..表示上级目录
     */
    public void findFile(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\javaFile\\..\\pythonFile");
        System.out.println(path);
        //路径正常化
        System.out.println(path.normalize());
    }

判断文件是否存在

    /**
     * 文件是否存在。
     */
    public void fileIsExists(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\c.txt");
        System.out.println(Files.exists(path));
    }

创建目录(不能创建多级目录)

    /**
     * 创建目录。
     * 只能创建一级目录,不能创建多级目录。
     * 如果目录存在,则会报错。
     */
    public void createOneFile() throws IOException {
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\htmlFile");
        Files.createDirectory(path);
    }

创建目录(能创建多级目录)

    /**
     * 创建目录。
     * 可以创建多级目录。
     * 如果目录存在,则不创建。
     */
    public void createFiles() throws IOException {
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\htmlFile\\a\\b");
        Files.createDirectories(path);
    }

拷贝文件

    /**
     * 拷贝文件
     */
    public void copyFileTest(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\a.txt");
        Path path1 = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\c.txt");
        try {
            //如果存在c.txt,则报错
            //Files.copy(path,path1);
            //如果存在c.txt,则覆盖(需要谨慎操作。)
            Files.copy(path,path1, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

移动文件

    /**
     * 移动文件
     */
    public void moveFileTest(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\b.txt");
        Path path1 = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\javaFile\\a.txt");
        try {
            //如果存在同名文件则报错
            //Files.move(path,path1);
            //如果存在同名文件则覆盖。
            Files.move(path,path1, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

删除文件或文件夹

    /**
     * 删除文件或文件夹(如果文件夹里还有内容,则会报错。)
     */
    public void deleteFileTest(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\htmlFile\\a");
        try {
            Files.delete(path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

遍历文件

    /**
     * 遍历所有文件
     */
    public void ergodicFiles(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程\\htmlFile\\a");
        AtomicInteger dirCount = new AtomicInteger();
        AtomicInteger fileCount = new AtomicInteger();
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
                //遍历到文件夹时走这个方法。
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    System.out.println("preVisitDirectory():"+dir);
                    dirCount.incrementAndGet();
                    return super.preVisitDirectory(dir, attrs);
                }
                //遍历到文件时走这个方法。
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException {
                    System.out.println("visitFile:"+file);
                    fileCount.incrementAndGet();
                    return super.visitFile(file, attrs);
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("文件夹数量:"+dirCount);
        System.out.println("文件数量:"+fileCount);
    }

删除文件夹下所有文件(慎重操作)

    /**
     * 删除文件夹下所有文件(慎重操作)
     */
    public void deleteAll(){
        Path path = Paths.get("C:\\Users\\20203\\Desktop\\网络编程");
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return super.visitFile(file, attrs);
                }
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                        throws IOException {
                    Files.delete(dir);
                    return super.postVisitDirectory(dir, exc);
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

拷贝多级文件

    /**
     * 拷贝多级文件
     */
    public void copyFilesTest(){
        String source = "C:\\Users\\20203\\Desktop\\网络编程\\来源文件夹";
        String target = "C:\\Users\\20203\\Desktop\\网络编程\\目标文件夹";
        try {
            Files.walk(Paths.get(source)).forEach(path -> {
                try {
                    String targetName = path.toString().replace(source, target);
                    // 是目录
                    if (Files.isDirectory(path) ) {
                        Files.createDirectory(Paths.get(targetName));
                    }
                    // 是普通文件
                    else if (Files.isRegularFile(path)) {
                        Files.copy(path, Paths.get(targetName));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值