File类和Date类的一些笔记

3.File类

1.基本属性

public boolean canRead()
public boolean exists()
public boolean isFile()
public long lastModified()
public String getName()
public boolean canWrite()
public boolean isDirectory()
public boolean isHidden()
public long length()
public String getPath()

2.常见方法

public boolean createNewFile()throws IOException
public boolean delete()
public boolean mkdir(), mkdirs()

3.DEMO演示

public class Common03 {
    //File类
    public static void main(String[] args) {
        File file = new File("e:/zhj123");
        File f2 = new File("e:/src3");
        File f3 = new File(f2, "TestFile.java");
        File f4 = new File(f2, "TestFile666.java");
        File f5 = new File("e:/src3/aa/bb/cc/dd");
        file.mkdir();//创建一个空文件夹
        f2.mkdir();
        f5.mkdirs();//创建多个子文件夹
        try {
            f3.createNewFile();//在已经创建文件夹的基础上新建一个文件
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (file.isFile()) {
            System.out.println("是一个文件!");
        }
        if (f2.isDirectory()) {
            System.out.println("是一个目录!");
        }
        if (f3.isFile()) {
            System.out.println("是一个文件奥");
        }

    }
}

PS:delete只能删除文件或者空的文件夹,如果文件夹里由目录,则必须先删除目录才能删除文件夹

4.Date类

1.构造函数

Date 类提供两个构造函数来实例化 Date 对象。

第一个构造函数使用当前日期和时间来初始化对象。

第二个构造函数接收一个参数,该参数是从1970年1月1日起的毫秒数。

2.常见方法

1 boolean after(Date date) 若当调用此方法的Date对象在指定日期之后返回true,否则返回
false。
2 boolean before(Date date) 若当调用此方法的Date对象在指定日期之前返回true,否则返
回false。
3 Object clone( ) 返回此对象的副本。
4 int compareTo(Date date) 比较当调用此方法的Date对象和指定日期。两者相等时候返回
0。调用对象在指定日期之前则返回负数。调用对象在指定日期之后则返回正数。
5 int compareTo(Object obj) 若obj是Date类型则操作等同于compareTo(Date) 。否则它抛
出ClassCastException。
6 boolean equals(Object date) 当调用此方法的Date对象和指定日期相等时候返回true,否
则返回false。
7 long getTime( ) 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒
数。
8 int hashCode( ) 返回此对象的哈希码值。
9 void setTime(long time) 用自1970年1月1日00:00:00 GMT以后time毫秒数设置时间和日
期。
10 String toString( ) 把此 Date 对象转换为以下形式的 String: dow mon dd hh:mm:ss zzz
yyyy 其中: dow 是一周中的某一天 (Sun, Mon, Tue, Wed, Thu, Fri, Sat)。

3.代码演示

public class Common04 {
    //Date类
    public static void main(String[] args) {
        // 初始化 Date 对象
        Date date = new Date();
        // 使用 toString() 函数显示日期时间
        System.out.println(date.toString());

        //比较两个对象
        long time = date.getTime();
        long time2 = date.getTime();
        System.out.println(time==time2);//true

        //before方法
        boolean before = new Date(99, 01, 12).before(new Date(99,01,20));
        System.out.println(before);//true

        //compareTo
        Date date1 = new Date(99,02,10);
        Date date2 = new Date();
        if (date2.compareTo(date1)>0){
            System.out.println("date2在date1后面");
        }

        //返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
        long time3 = date2.getTime();
        System.out.println(time3);


    }
}
posted @ 2022-07-06 17:00  风雨2  阅读(50)  评论(0)    收藏  举报