子路 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());

}

}

结果

c3a5f69c8edd14a0b9c1374f6324e123.png

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

绝对路径:从盘符开始的路径,这是一个完整的路径。

相对路径:相对于项目目录的路径,这是一个便捷的路径,开发中经常使用。

判断功能的方法

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());

}

}

结果

87c1c2fb5fbf92322ccf2aea04a0258b.png

创建删除功能的方法

public boolean createNewFile() :当且仅当具有该名称的文件尚不存在的时候,创建一个新的空文件(注意不是文件夹)

public boolean delete():删除由此File表示的目录或文件

public boolean mkdir():创建由此File表示的目录,

public boolean mkdirs():创建由此File表示的目录,包括任何必须但是不存在的目录

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

6d22334aa11ae036fa2242025c7c1a4f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值