绝对路径与相对路径
一、项目中的绝对路径(absolutePath)和相对路径(relativePath)简述
好多初学者问我相对路径的问题,所以在这里对绝对路径和相对路径做一个简单的讲解,希望对初学者有所帮助。
二、举个栗子来说明
首先我们的IDE使用IDEA,搭建一个简单的maven项目,目录结构如下:
以本项目中user.properties文件为栗子
absolutePath:它的绝对路径是指在计算机硬盘上的物理路径,比如在我电脑上的绝对路径就是:C:\pathStu\src\main\resources\conf\user.properties。
relativePath:对于很多同学难以理解,贴一段代码,看注释吧。
package com.alex;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* @author alex
* @Title: Example
* @Description: TODO
* @date 2019/3/5 18:04
*/
public class Example {
public static void main(String[] args) throws IOException {
one();
}
public static void one() throws IOException {
/**
* 相对路径:
* A:user.properties的相对路径相对于谁呢?
* B:你在哪里想找user.properties文件,那么就相对于当前这个文件,比如这里在Example.class文件中找
* user.properties文件,那么当前文件就是Example.class。(注意:这里为什么不写Example.java呢?
* 因为程序运行时执行的是编译后的.class文件)。
* A:../../conf/user.properties,应该怎么解读呢?
* B:首先我们要知道"../"表示返回上一级目录的意思。当前文件Example.class
* 所在的目录是pathStu/classes/com/alex。relativePath路径是相对于当前文件,而当前文件所在目录是pathStu/classes/com/alex。
* 所以,relativePath表示的路径是pathStu/classes/com/alex/../../conf/user.properties,我们访问这个的时候
* 是这样的,首先进入pathStu目录,然后进入classes目录,然后进入com目录,然后进入alex目录,然后返回上一级目到com
* 目录,然后返回上一级到classes目录,然后进入conf目录,这样就找到了user.properties文件。现在你会发现,我们虽然写了pathStu这个目录,但在我们找user.properties文件时,我们根本没有用到这个目录,找到classes目录就开始向里面找conf目录了。
*/
String relativePath = "../../conf/user.properties";
URL resource = Example.class.getResource(relativePath);
InputStream inputStream = resource.openStream();
byte[] ch = new byte[inputStream.available()];
inputStream.read(ch,0,inputStream.available());
System.out.println(new String(ch));
inputStream.close();
}
}
通过上面的代码注释,希望可以让你对相对路径有所理解。