Java学习笔记15 IO操作

java中我们通过java.io.File类实现对文件的基本属性进行操作,包括文件属性读取,文件创建,文件删除,文件添加等等。File是一个类,那么在使用的时候就需要创建对象,但是File类的实例是不可变的,也就是说,一旦创建,由File对象表示的抽象路径名将永远不会改变,也就是说利用构造方法,指定路径名、文件名等来构造File类的对象,之后调用该对象的createNewFile()方法就可以创建出相应的文件。

File类的对象可以代表一个具体的文件路径,在实际运用种,可以使用绝对路径也可以使用相对路径,下面是创建文件对象实例。

构造方法 说明
new File(“d:\test\test.txt”) 指定的目录下建立文件,如果路径不存在,则建立虚拟file对象
new File(“test.txt”) 在当前项目根目录下建立文件 test.txt
new File(“d:\test”) test可以是个目录,也可能是个文件
new File(“d:\test\”,“test.dat”) 指定目录下,建立指定的文件
方法 说明
File.delete() 删除文件或空目录文件夹目录
File.createNewFile() 创建一个新的空文件
File.mkdir() 创建一个新的空文件夹
File.mkdirs() 批量建立多级目录
File.list() 获取指定目录下的文件和文件夹名称
File.listFiles() 获取指定目录下的文件和文件夹对象
File.exists() 文件或者文件夹是否存在
String getParent() 返回父目录的路径名字符串;如果没有指定父目录,则返回 null
File getParentFile() 返回父目录File对象
String getName() 返回文件或文件夹的名称
String getAbsolutePath() 获取绝对路径
String getPath() 返回路径名字符串
long lastModified() 返回文件最后一次被修改的时间
long length() 获取长度,字节数
boolean canRead() 判断是否可读
boolean canWrite() 判断是否可写
boolean isHidden() 判断是否隐藏
long getFreeSpace() 返回分区中未分配的字节数
long getTotalSpace() 返回此文件分区大小
long getUsableSpace() 返回占用字节数
int hashCode() 文件哈希码
方法 说明
static File[] listRoots() 列出可用的文件系统根
boolean renameTo(File dest) 重命名,剪切粘贴文件,移动文件
boolean setExecutable(boolean executable) 设置执行权限
boolean setExecutable(boolean executable, boolean ownerOnly) 设置其他所有用户的执行权限
boolean setLastModified(long time) 设置最后一次修改时间
boolean setReadable(boolean readable) 设置读权限
boolean setReadable(boolean readable, boolean ownerOnly) 设置其他所有用户的读权限
boolean setWritable(boolean writable) 设置写权限
boolean setWritable(boolean writable, boolean ownerOnly) 设置所有用户的写权限

File类的直接父类是Object类。一个File类的对象,表示了磁盘上的文件或目录。如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目根路径下。

检索一个目录下的所有文件

 public static void count(File f) {
    
    
        File[] files = f.listFiles();
        for (File f1 : files) {
    
    
            if (f1.isDirectory()) {
    
    
                count(f1);
            }
            System.out.printf("文件:%s[%s]%n", f1.getAbsolutePath(), f1.isFile() ? "文件" : "目录");
        }
    }

删除一个目录下的文件

public static void deltree(File dir) {
    
    
        if (dir.isDirectory()) {
    
    
            File[] files = dir.listFiles();
            for (File f : files) {
    
    
                if (f.isDirectory()) {
    
    
                    deltree(f);
                }
                f.delete();
            }
        }
        dir.delete();
    }

统计每种文件在文件夹中出现的次数。

static Map<String, Integer> map = new HashMap<>();

    public static void main(String[] args) {
    
    

        count1(new File("H:\\weixinProjects"));
        System.out.println(map);
    }

    public static void count1(File f) {
    
    
        File[] files = f.listFiles();
        for (File f1 : files) {
    
    
            if (f1.isDirectory()) {
    
    
                count1(f1);
            }
            if (f1.isFile()) {
    
    
                String fn = f1.getName().toLowerCase();
                String exit = "unknow";
                try {
    
    
                    exit = fn.substring(fn.lastIndexOf("."));
                } catch (Exception e) {
    
    

                }
                if (map.containsKey(exit)) {
    
    
                    map.put(exit, map.get(exit) + 1);
                } else {
    
    
                    map.put(exit, 1);
                }
            }
        }
    }

整理文件

static Set<String> types = new HashSet<>(List.of("jpg", "png", "webp", "gif", "svg"));
    static long num = 0;


    public static void count2(File dir, File dst) {
    
    
        if (!dst.exists()) {
    
    
            dst.mkdirs();
        }
        if (dir.isDirectory()) {
    
    
            File[] files = dir.listFiles();
            for (File f : files) {
    
    
                if (f.isDirectory()) {
    
    
                    count2(f, dst);
                }
                String fn = f.getName().toLowerCase();
                String ext = fn.substring(fn.lastIndexOf(".") + 1);
                if (types.contains(ext)) {
    
    
                    copyFile(f, new File(dir, String.format("wx-%03d.%s", ++num, ext)));
                }
            }
        } else {
    
    
            String fn = dir.getName().toLowerCase();
            String ext = fn.substring(fn.lastIndexOf(".") + 1);
            copyFile(dir, new File(dir, String.format("wx-%03d.%s", ++num, ext)));
        }
    }

    public static void copyFile(String src, String dst) {
    
    
        copyFile(new File(src), new File(dst), 8192);
    }

    public static void copyFile(File src, File dst) {
    
    
        copyFile(src, dst, 8192);
    }


    public static void copyFile(File src, File dst, int b) {
    
    
        try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst)) {
    
    
            byte[] buf = new byte[b];
            int len = 0;
            while ((len = fis.read(buf)) >= 0) {
    
    
                fos.write(buf, 0, len);
            }
        } catch (Exception e) {
    
    

        }
    }

写一个程序统计代码行

 static long AllRows = 0;
    static int AllFiles = 0;

    public static void main(String[] args) {
    
    
        count(new File("G:\\javaEE\\Javase\\proa01"));
    }

    public static void count(File src) {
    
    
        File[] files = src.listFiles();
        for (File f : files) {
    
    
            if (f.isDirectory()) {
    
    
                count(f);
            }
            if (f.getName().endsWith("java")) {
    
    
                long rows = getRows(f);
                AllRows += rows;
                AllFiles++;
                System.out.println(f.getAbsolutePath() + "[有" + rows + "行]");
                System.out.println("总共有" + AllRows);
                System.out.println("Java文件有" + AllFiles);

            }
        }
    }

    public static long getRows(String src) {
    
    
        return getRows(new File(src));
    }

    public static long getRows(File src) {
    
    
        long rows = 0;
        try (var read = new FileInputStream(src)) {
    
    
            rows = new String(read.readAllBytes()).lines().count();
        } catch (Exception e) {
    
    

        }
        return rows;
    }

猜你喜欢

转载自blog.csdn.net/xxxmou/article/details/129207837
今日推荐