首页 课程 师资 教程 报名

一文读懂Java相对路径怎么写

  • 2022-09-02 11:52:17
  • 6201次 动力节点

本教程介绍如何在 Java 中定义相对路径。

相对路径是不完整的路径(没有根目录),结合当前目录路径访问资源文件。相对路径不以文件系统的根元素开头。

我们使用相对路径来定位文件在当前目录或父目录,或同一层次结构中。

定义相对路径有几种方法,例如./引用当前目录路径,../直接父目录路径等。让我们看一些例子。

在Java中定义一个相对路径来定位文件

我们可以使用相对路径来定位当前工作目录中的文件资源。请参见下面的示例。

import java.io.File;
public class SimpleTesting{
    public static void main(String[] args) { 
        String filePath = "files/record.txt";
        File file = new File(filePath);
        String path = file.getPath();
        System.out.println(path);
    }
}

输出:

files/record.txt

在 Java 中定义父目录的相对路径

我们可以使用../带有文件路径的前缀来定位父目录中的文件。这是访问父目录中文件的相对路径。请参见下面的示例。

import java.io.File;
public class SimpleTesting{
    public static void main(String[] args) { 
        String filePath = "../files/record.txt";
        File file = new File(filePath);
        String path = file.getPath();
        System.out.println(path);
    }
}

输出:

../files/record.txt

在 Java 中定义当前目录中的相对路径

如果文件资源位于当前目录,我们可以使用./带路径的前缀来创建相对文件路径。请参见下面的示例。

import java.io.File;
public class SimpleTesting{
    public static void main(String[] args) { 
        String filePath = "./data-files/record.txt";
        File file = new File(filePath);
        String path = file.getPath();
        System.out.println(path);
    }
}

输出:

./data-files/record.txt

../../在 Java 中使用前缀定义相对路径

如果文件位于目录结构的上两层,则使用../../带有文件路径的前缀。请参见下面的示例。

import java.io.File;
public class SimpleTesting{
    public static void main(String[] args) { 
        String filePath = "../../data-files/record.txt";
        File file = new File(filePath);
        String path = file.getPath();
        System.out.println(path);
        String absPath = file.getAbsolutePath();
        System.out.println(absPath);
    }
}

输出:

../../data-files/record.txt

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交