zoukankan      html  css  js  c++  java
  • 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类的一些基础知识如有错误还请各位批评指正,喜欢我的文章的可以关注我,或者点赞收藏

    在这里插入图片描述

  • 相关阅读:
    真正的Java学习从入门到精通
    Java学习从入门到精通(1) [转载]
    Java Learning Path(三)过程篇
    Java Learning Path(五)资源篇
    Java Learning Path(四) 方法篇
    浅析Java语言中两种异常的差别
    JDK,JRE,JVM区别与联系
    JAVA敏捷开发环境搭建
    谈谈WEB开发中的苦大难字符集问题
    java读取clob字段的几种方法
  • 原文地址:https://www.cnblogs.com/pjhaymy/p/13324583.html
Copyright © 2011-2022 走看看