Java | File class

File class

  • File classRepresents: An abstract representation of file and directory pathnames . ( File can be a file or a directory )
  • The File class has nothing to do with the IO stream . The File class cannot complete reading and writing files .

Commonly used methods in the File class:

boolean exists(): Determine whether this file/directory exists

   //创建File对象
   File f1 = new File("D:///Apple.txt");

   //判断文件是否存在 
   boolean b = f1.exists();
   System.out.println(b);

boolean createNewFile(): Create a file

  //创建File对象
  File f1 = new File("D:/Apple123.txt");

  //创建一个txt文件 ( 在D盘下创建一个Apple.txt文件 )
  boolean b = f1.createNewFile();
  System.out.println(b);

boolean mkdir(): Create a "single-layer" directory/folder

  • mkdir( ):Create" single layer "Table of contents.
    That is, only one directory/folder can be created at a time . If there are multiple directories in the path , the creation will fail .

    Examples include:

       //创建File对象
       File f1 = new File("D:/App168.txt");
      /**
       * 创建一个目录/文件夹 ( 在D盘下创建一个名为: Apple.txt 的目录/文件夹)
       *
       * "D:\\Apple.txt" : 只有一层 “未创建”目录,此时可创建且不报错
       */
       boolean b =f1.mkdir(); //创建“单层”目录
       System.out.println(b);
    

boolean mkdirs(): Create "multi-layer" directories/folders

  • mkdirs( ):Create" Multiple layers "Table of contents. How many directories/files are created in the path .

    Examples include:

      //创建File对象
      File f1 = new File("D:/aaa/bbb/ccc");
    
      boolean b =f1.mkdirs(); //创建“多层”目录
      System.out.println(b);
    

File[ ] listFiles( ): Get all File objects "under the current path"

  • listFiles( )Method: Get all File objects " under the current path" . The method return value is a File array .

  • ps : The File object can be a directory/folder or a file .

       File f = new File("D:/apple");
       //获取“当前路径下”的所有File对象
       File[] files = f.listFiles();
       for (File file : files) {
           
           
       System.out.println(file.getAbsolutePath());  //获得真实路径
    

Copy directory: Copy "all subfolders and files" under the specified "folder" (to "other paths")

  • Copy directory : Copy " all subfolders and files " under the specified " folder " (to " other paths ")

    Examples include:
    (There are annotated examples and concise/less annotated examples )

    /**
     *  拷贝目录
     */
    public class CopyAll4 {
           
           
        public static void main(String[] args) {
           
           
            /**
             * 目的的:
             * 将 D:\\apple目录下的所有子目录或文件 复制一份 且放到  S:\\123 路径下
             */
            //拷贝源
            File srcFile = new File("D:\\apple");
    
            //拷贝目标
            File tarFile = new File("S:\\123");
    
            try {
           
           
                //调用方法完成 “目录拷贝”
                copyDir(srcFile,tarFile);
    
            } catch (IOException e) {
           
           
                e.printStackTrace();
            }
    
        }
    
        /**
         *
         * @param srcFile 拷贝源
         * @param tarFile 拷贝目标 (要复制到具体哪个盘符下的 什么文件夹)
         */
        private static void copyDir(File srcFile, File tarFile) throws IOException {
           
           
            //判断该File对象是否是“文件”
            //如果是文件要进行“读”和“写” , 如果不是则跳过该if语句,执行下面代码
            if (srcFile.isFile()) {
           
           
                //是文件进行"读"和"写"
                FileInputStream in = null;
                FileOutputStream out = null;
    
                in = new FileInputStream(srcFile);
    
                /**
                 *  通过拼接得到 “要被写入信息” 的 “文件的路径”
                 *
                 *  如: D:\\apple\\aaa\\ccc\\123.txt
                 *  结合目标目录: S:\\123 那就要拼接出 : S:\\123 + \\ + 			   	 			*  apple\\aaa\\ccc\\123.txt
                 *  拼接代码如下,拼接得到的path被用于创建 FileOutputStream 中
                 */
                // D:\\apple\\aaa\\ccc\\123.txt
                // S:\\123 + \\ + apple\\aaa\\ccc\\123.txt
                String path = tarFile.getAbsolutePath().endsWith("\\") ? tarFile.getAbsolutePath() : tarFile.getAbsolutePath() + "\\" + srcFile.getAbsolutePath().substring(3);
                byte[] bytes = new byte[1024 * 1024];  //一次复制1MB
    
                int readCount = 0;  // read(bytes)方法返回值为: 读取的字节数
                out = new FileOutputStream(path);
                while ((readCount = in.read(bytes)) != -1) {
           
           
                    //边读边写
                out.write(bytes,0,readCount); //读到多少就写多少
            }
                //刷新流
                out.flush();
                return;
        }
    
            //获得该目录下的所有File对象
            File[] files = srcFile.listFiles();
             for (File file : files) {
           
           
                //判断该File对象是否是文件夹/目录
                //如果该File对象是一个文件夹,要对其进行创建。(同时也要在if语句之后用递归,因		       为文件夹中可能也有子文件夹或子文件)
                if (file.isDirectory()) {
           
           
    
                    //获得此时File对象的 真实路径
                    String srcDir = file.getAbsolutePath();
                    //拼接出要创建的目录/文件夹的 路径,然后创建紧接着创建该目录
                    // S:\\123 + \\ + apple\\aaa
                    String tarDir = tarFile.getAbsolutePath().endsWith("\\") ? tarFile.getAbsolutePath() : tarFile.getAbsolutePath() +"\\" + srcDir.substring(3);
                    //创建该目录
                    File newFile = new File(tarDir); // S:\\123\\apple\\aaa
                    newFile.mkdirs();
                    //在if语句外面进行递归,无论该File对象是文件夹 还是 文件,都要进行递归。
                }
    
                //无论循环中的File对象是文件夹还是文件都要进行递归。为其创建子目录 或 子文件
                // 因为是文件夹,所以还要进去文件夹中判断里面是否还有子文件夹 或 子文件 : 递归
                //方法递归
                copyDir(file,tarFile);
            }
        }
    }
    

    Concise version/uncommented version :

    /**
     *  拷贝目录
     */
    public class CopyAll4 {
           
           
        public static void main(String[] args) {
           
           
            /**
             * 目的的:
             * 将 D:\\apple目录下的所有子目录或文件 复制一份 且放到  S:\\123 路径下
             */
            //拷贝源
            File srcFile = new File("D:\\apple");
    
            //拷贝目标
            File tarFile = new File("S:\\123");
    
            try {
           
           
                //调用方法完成 “目录拷贝”
                copyDir(srcFile,tarFile);
    
            } catch (IOException e) {
           
           
                e.printStackTrace();
            }
    
        }
    
        /**
         *
         * @param srcFile 拷贝源
         * @param tarFile 拷贝目标 (要复制到具体哪个盘符下的 什么文件夹)
         */
        private static void copyDir(File srcFile, File tarFile) throws IOException {
           
           
            //判断该File对象是否是“文件”
            if (srcFile.isFile()) {
           
           
                //是文件进行"读"和"写"
                FileInputStream in = null;
                FileOutputStream out = null;
    
                in = new FileInputStream(srcFile);
    
                /**
                 *  通过拼接得到 “要被写入信息” 的 “文件的路径”
                 */
                // D:\\apple\\aaa\\ccc\\123.txt
                // S:\\123 + \\ + apple\\aaa\\ccc\\123.txt
                String path = tarFile.getAbsolutePath().endsWith("\\") ? tarFile.getAbsolutePath() : tarFile.getAbsolutePath() + "\\" + srcFile.getAbsolutePath().substring(3);
                byte[] bytes = new byte[1024 * 1024];  //一次复制1MB
    
                int readCount = 0;  // read(bytes)方法返回值为: 读取的字节数
                out = new FileOutputStream(path);
                while ((readCount = in.read(bytes)) != -1) {
           
           
                    //边读边写
                    out.write(bytes,0,readCount); //读到多少就写多少
                }
                //刷新流
                out.flush();
                return;
            }
    
            //获得该目录下的所有File对象
            File[] files = srcFile.listFiles();
            for (File file : files) {
           
           
                //判断该File对象是否是文件夹/目录
                if (file.isDirectory()) {
           
           
    
                    //获得此时File对象的 真实路径
                    String srcDir = file.getAbsolutePath();
                    String tarDir = tarFile.getAbsolutePath().endsWith("\\") ? tarFile.getAbsolutePath() : tarFile.getAbsolutePath() +"\\" + srcDir.substring(3);
                    //创建该目录
                    File newFile = new File(tarDir); // S:\\123\\apple\\aaa
                    newFile.mkdirs();
                }
    
                copyDir(file,tarFile);
            }
        }
    }
    

String getParent(): Get the "parent path" of the specified "file/directory"

  • getParent( ): Get the " parent path " of the specified "file/directory" . The return value is String type. If it has no parent path , null is returned .

       File f1 = new File("D:/aaa/bbb/ccc/App168.txt");
       //获得指定 “文件/目录”的 “父路径”
       String parent1 = f1.getParent();
       System.out.println(parent1); // 输出路径为: D:/aaa/bbb/ccc
    
    
       System.out.println();
       File f2 = new File("D:/aaa/bbb/ccc");
       //获得指定 “文件/目录”的 “父路径”
       String parent2 = f2.getParent();
       System.out.println(parent2); // 输出路径为: D:/aaa/bbb
    
    
       System.out.println();
       File f3 = new File("D:/aaa/bbb");
       //获得指定 “文件/目录”的 “父路径”
       String parent3 = f3.getParent();
       System.out.println(parent3); // 输出路径为: D:/aaa
    

File getParentFile(): Get the "parent path" of the specified "file/directory"

  • getParentFile( ): Get the " parent path " of the specified "file/directory" . The return value is a File object, or null if it has no parent path .

    Examples include:

       File f1 = new File("D:\\aaa\\bbb\\ccc\\App168.txt");
       //获得指定 “文件/目录”的 “父路径”,返回值为File对象
       File parentFile = f1.getParentFile(); //此时其路径为:  D:\aaa\bbb\ccc
       //获得绝对路径
       String path =parentFile.getAbsolutePath();
       System.out.println(path); // 输出路径为: D:\aaa\bbb\ccc
    

String getAbsolutePath(): Get the absolute path

   File f1 = new File("D:\\aaa\\bbb\\ccc\\App168.txt");
   //获得绝对路径
   String path =f1.getAbsolutePath();
   System.out.println(path); // 输出路径为: D:\aaa\bbb\ccc\App168.txt

boolean delete(): delete files/directories

  File f = new File("D:\\aaa\\file.txt");
  // 删除文件/目录
  boolean b = f.delete(); //把file.txt给删除
  System.out.println(b); //true

String getName(): Get the name of the file/path

  File f = new File("D:/file.txt");
  // 获取 文件/路径 的名称
  String name = f.getName();
  System.out.println(name); // file.txt

boolean isDirectory(): Determine whether it is a directory/folder

   File f = new File("D:/file.txt");
   // 判断是否是一个目录/文件夹
   boolean b = f.isDirectory();
   System.out.println(b);  //false

boolean isFile(): Determine whether it is a file

   File f = new File("D:/file.txt");
   // 判断是否是一个文件
   boolean b = f.isFile();
   System.out.println(b);  //true

long lastModified(): Get the last modification time of the file (number of milliseconds)

   File f = new File("D:/file1.txt");
   // 获得文件最后一次修改时间
   long time = f.lastModified();//这个毫秒是从1970年到现在的总毫秒数
   //将总毫秒数转换为日期
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SS");
   String strTime = sdf.format(time);
   System.out.println(strTime);

long length(): Get file size

  File f = new File("D:/file.txt");
  // 获取文件大小
  long length = f.length();
  System.out.println(length);

Guess you like

Origin blog.csdn.net/m0_70720417/article/details/132644337