Java File类基础解析 1

时间:2022-07-25
本文章向大家介绍Java File类基础解析 1,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Java File类基础解析 1

File类的构造方法

public File(String pathname) :通过给定的路径名字符转换为抽象路径名来创建新的File实例

    String path = new String("D:\a.text");
    File file = new File(path);

public File(String parent,String child) :从父路径字符串和子路路径字符串来创建新的File实例

    String parentpath = new String("D:\a.text");
    String childpath = new String("a.text");
    File file = new File(parentpath,childpath);

public File(File parent, String child) :从父抽象路径名和子路径名字符串创建新的 File实例。

    String parentpath = new String("D:\a");
    String childpath=new String("b.text");
    File file = new File(parentpath);
    File file1 = new File(file, childpath);
    System.out.println(file1.getAbsolutePath());

File类常用方法

获取功能方法 public String getAbsolutePath() :返回此File的绝对路径名字符串。 public String getPath() :将此File转换为路径名字符串。 public String getName() :返回由此File表示的文件或目录的名称。 public long length() :返回由此File表示的文件的长度。

代码演示

package File;
import java.io.File;
public class Main {
    public static void main(String[] args) {
        String parentpath = new String("D:\a");
        String childpath=new String("b.text");
        File file = new File(parentpath,childpath);
        System.out.println("获取绝对路径:"+file.getAbsolutePath());
        System.out.println("获取构造路径:"+file.getPath());
        System.out.println("获取文件名称:"+file.getName());
        System.out.println("获取文件长度:"+file.length());
    }
}

结果

绝对路径与相对路径的区别

绝对路径:从盘符开始的路径,这是一个完整的路径。 相对路径:相对于项目目录的路径,这是一个便捷的路径,开发中经常使用。

判断功能的方法

public boolean exists() 此File表示文件或目录是否实际存在 public boolean isDirectory():此File表示是否为目录 public boolean isFile():此File表示的是否为文件

代码演示

public class Main {
    public static void main(String[] args) {
        String parentpath = new String("D:\test2\a");
        File file = new File(parentpath);
        System.out.println("是否为目录:"+file.isDirectory());
        System.out.println("是否为文件:"+file.isFile());
        System.out.println("是否存在:"+file.exists());
    }
}

结果

创建删除功能的方法

public boolean createNewFile() :当且仅当具有该名称的文件尚不存在的时候,创建一个新的空文件(注意不是文件夹) public boolean delete():删除由此File表示的目录或文件 public boolean mkdir():创建由此File表示的目录, public boolean mkdirs():创建由此File表示的目录,包括任何必须但是不存在的目录

以上就是javaFile类的一些基础知识如有错误还请各位批评指正,喜欢我的文章的可以关注我,或者点赞收藏