Java文件的基本概念

本文介绍了Java中File类的使用,包括路径的概念,如绝对路径、相对路径和规范化路径的区别。通过示例代码展示了如何获取和操作这些路径。同时,提到了简化路径的LeetCode题目71-简化路径。File类用于抽象文件系统,提供了创建、检查文件或目录的方法。建议使用File.separator确保跨平台兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1 路径

在IO中,常用到路径的概念,有以下几种路径:

  1. c:\temp\file.txt
  2. .\file.txt
  3. c:\temp\MyApp\bin…\file.txt

第一类,属于路径,绝对路径,规范路径 (CanonicalPath)
第二类,属于路径,相对路径(Path)
第三类,属于路径,绝对路径 (AbsolutePath)

下面的示例代码清楚的展示了java中这三类路径的区别

/* -------这是一个相对路径的代码------- */
File file = new File("..\\..\\..\\Test.txt");
System.out.println("file.getAbsolutePath()  -> " + file.getAbsolutePath());
System.out.println("file.getCanonicalPath() -> " + file.getCanonicalPath());
System.out.println("file.getPath()          -> " + file.getPath());

/* -------输出------- */
file.getAbsolutePath()  -> E:\commonWorkspace\IdeaPluginDevGuide\DevGuideVirtualFileSystem\..\..\..\Test.txt
file.getCanonicalPath() -> E:\Test.txt
file.getPath()          -> ..\..\..\Test.txt

可以看到Path就是创建File时使用的相对目录。AbsolutePath是绝对路径,其中可能包含…/ or ./这类切换目录的相对目录,而CanonicalPath就是规范化后的绝对路径。leetcode有一题就是规范化路径的,71-简化路径,链接如下

https://leetcode-cn.com/problems/simplify-path/

1.2 File类

该类主要用来抽象文件系统,并对其进行操作,类似于Linux的ls命令。

为了代码可以在多种操作系统上创建文件对象,目录中的分隔符建议采用File.separator。

String fileName = "test.txt";
        System.out.println("File.separator:" + File.separator);
        File testFile = new File("D:" + File.separator + "filepath" + File.separator + "test" + File.separator + fileName);
        File fileParent = testFile.getParentFile();//返回的是File类型,可以调用exsit()等方法
        String fileParentPath = testFile.getParent();//返回的是String类型
        System.out.println("fileParent:" + fileParent);
        System.out.println("fileParentPath:" + fileParentPath);
        if (!fileParent.exists()) {
            fileParent.mkdirs();// 能创建多级目录
        }
        if (!testFile.exists()){
            try {
                testFile.createNewFile();//有路径才能创建文件
            }catch (IOException e){
                e.printStackTrace();
            }
        }

        System.out.println(testFile);

        String path = testFile.getPath();
        String absolutePath = testFile.getAbsolutePath();//得到文件/文件夹的绝对路径
        String getFileName = testFile.getName();//得到文件/文件夹的名字
        System.out.println("path:"+path);
        System.out.println("absolutePath:"+absolutePath);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值