IO流-File

版权声明:有一种生活不去经历不知其中艰辛,有一种艰辛不去体会,不会知道其中快乐,有一种快乐,没有拥有不知其中纯粹 https://blog.csdn.net/wwwzydcom/article/details/85047067

java.io.File类概述

1.凡是与输入,输出相关的类,接口等都定义在java.io包下

2.File是一个类,可以有构造器创建其对象,此对象对应一个文件或者目录

3.File类对象是与平台无关的

4.File中的方法,只涉及到如何创建,删除,重命名等等,涉及到修改文件内容,必须使用Io流来完成

基本的方法:

访问文件名

getName() :获取文件名

getPath():获取文件路径

getAbsoluteFile():获取绝对路径+文件名

getAbsolutePath():获取绝对路径

getParent():获取上一级目录

rename To(File newName):重命名

代码

File file1 = new File("F:\\test\\websit.log");
File file2 = new File("hello.txt");

System.out.println(file1.getName());
System.out.println(file1.getPath());
System.out.println(file1.getAbsoluteFile());
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getParent());
/*
结果:
websit.log
F:\test\websit.log
F:\test\websit.log
F:\test\websit.log
F:\test
 */
System.out.println(file2.getName());
System.out.println(file2.getPath());
System.out.println(file2.getAbsoluteFile());
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getParent());
/*
hello.txt
hello.txt
F:\学习资料\后期学习\spark\12.7\es\hello.txt
F:\学习资料\后期学习\spark\12.7\es\hello.txt
null
 */

renameTo(File newName):重命名

file1.renameTo(file2) : file1重命名为file2,要求file1文件一定存在,file2文件一定不存在

文件检测

exists()

canWrite()

canRead()

isFile()

isDirectory()

获取常规文件信息

lastModified() //最后修改的时间

length() //文件的大小

@Test
public void test01(){
    File file1 = new File("F:\\test\\websit.log");
    File file2 = new File("hello.txt");

    System.out.println(file2.exists());
    System.out.println(file2.canWrite());
    System.out.println(file2.isFile());
    System.out.println(file2.isDirectory());
    System.out.println(new Date(file2.lastModified()));
    System.out.println(file2.length());
    /*
    结果
    true
    true
    true
    false
    1544700613614
    2973
     */
}

目录操作相关

mkDir()

mkDirs()

list():列出文件夹下的目录信息

listFiles() :返回的是一个file对象

@Test
public void test03() throws IOException {
    File file1 = new File("F:\\test");
    if (!file1.exists()){
      file1.mkdir();//只有当上层文件目录存在的情况下返回true
      //file1.mkdirs(); 创建多级目录,上层目录不存在,一同创建
    }
    //列出文件夹下的目录信息
    String[] list = file1.list();
    for (String s : list) {
        System.out.println(s);
    }

    File[] files = file1.listFiles();
    for (File file : files) {
        System.out.println(file.getName());
    }
}

文件操作相关

createNewFile()

delete()

@Test
public void test02() throws IOException {
    File file1 = new File("F:\\test\\test.txt");
    if (!file1.exists()){
        boolean newFile = file1.createNewFile();
        System.out.println(newFile);
    }
    file1.delete();
}

猜你喜欢

转载自blog.csdn.net/wwwzydcom/article/details/85047067