Home>

•file class

1. It is only used for information (name, size, etc.) indicating a file (directory), and cannot be used to access the contents of the file.

package cn.test;
import java.io.file;
import java.io.ioexception;
public class demo16 {
  public static void main (string [] args) {
    file file=new file ("f:\\ javaio");
    //Whether the file (directory) exists
    if (! file.exists ()) {
      //Create a directory
      file.mkdir ();//file.mkdirs ();
    } else {
      //File (directory) delete
      file.delete ();
    }
    //Whether it is a directory Returns true if it is a directory, false if it is not a directory or the directory does not exist
    system.out.println (file.isdirectory ());
    //whether it is a file
    system.out.println (file.isfile ());
    //file file2=new file ("f:\\ java \\diary 1.txt");
    file file2=new file ("f:\\ javaio", "Diary 2.txt");
    if (! file2.exists ()) {
      try {
        //Create a file
        file2.createnewfile ();
      } catch (ioexception e) {
        e.printstacktrace ();
      }
    } else {
      file2.delete ();
    }
    system.out.println (file);
    system.out.println (file.getabsolutepath ());//Return the absolute path
    system.out.println (file.getname ());//directory name
    system.out.println (file2.getname ());//file name
    system.out.println (file.getparent ());//The path to the parent directory
    system.out.println (file.getparent ());//The path to the parent directory
  }
}

2. Traversing the directory

package com.test.io;
import java.io.file;
import java.io.ioexception;
/**
 * Common operations of the file class
 * @author administrator
 *
 * /
public class fileutils {
  /**
   * List all files in the specified directory (including its subdirectories)
   * @param dir
   * @throws ioexception
   * /
  public static void listdirectory (file dir) throws ioexception {
    if (! dir.exists ()) {
      throw new illegalargumentexception ("directory" + dir + "does not exist");
    }
    if (! dir.isdirectory ()) {
      throw new illegalargumentexception (dir + "Not a directory");
    }
    /* string [] filenames=dir.list ();//An array of strings is returned,List subdirectories and files in the current directory (not including the contents of subdirectories)
    for (string string:filenames) {
      system.out.println (dir + "\\" + string);
    } * /
    //If i want to traverse the contents of the subdirectory,You need to construct the file object for recursive operations
    file [] files=dir.listfiles ();//Returns the abstraction of direct subdirectories (files)
    if (files!=null&&files.length>0) {
      for (file file:files) {
        if (file.isdirectory ()) {
          //recursive
          listdirectory (file);
        } else {
          system.out.println (file);
        }
      }
    }
  }
}
  • Previous JSON usage of PHP array to JS array, how JS receives PHP array
  • Next Javascript to achieve smart navigation when page scrolling