Java基础(二十五)Java IO(2)文件File类

  File类是一个与流无关的类。File类的对象可以获取文件及其文件所在的目录、文件的长度等信息。

  1.File对象的常用构造方法。

  (1)File(String pathname)

File file2 = new File("D:\\FileTest\\FileTest.txt");

  (2)File(String path, String filename)

File file2 = new File("D:\\FileTest\\FileTest.txt");

  (3)File(File file, String filename)

File file_parent = new File("D:\\FileTest\\");
File file3 = new File(file_parent,"FileTest.txt");

 

  2.FIle类常用方法

  

 

  3.举例

  • 代码
package jun.iplab.file;

import java.io.File;

public class FileTest {
    
    public static void main(String[] args) {
        File file1 = new File("D:\\FileTest\\", "FileTest.txt");
        File file2 = new File("D:\\FileTest\\FileTest.txt");
        File file_parent = new File("D:\\FileTest\\");
        File file3 = new File(file_parent,"FileTest.txt");
        System.out.println(file1.exists());
        System.out.println(file2.exists());
        System.out.println(file3.exists());
        System.out.println();
        
        File file_not_exists = new File("D:\\FileTest\\FileTest1.txt");
        System.out.println(file_not_exists.exists());
        if (!file_not_exists.exists()) {
            file_not_exists.mkdirs();
        }
        System.out.println(file_not_exists.exists());
        System.out.println();
        
        System.out.println(file1.getName());
        System.out.println(file_not_exists.getName());
        System.out.println(file1.getAbsolutePath());
        System.out.println(file1.getPath());
        System.out.println(file1.length() + "B");
        System.out.println(file1.delete());
        System.out.println(file1.exists());
    }
}
  • 输出
false
false
false

true
true

FileTest.txt
FileTest1.txt
D:\FileTest\FileTest.txt
D:\FileTest\FileTest.txt
0B
false
false

 

posted @ 2018-08-02 17:14  BigJunOba  阅读(203)  评论(0编辑  收藏  举报