This article has shared with you how to obtain different paths in Java for your reference. The specific content is as follows
package com.ygh.blog.realpath;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Properties;/** * Demonstration of getting the path below java*/import org.junit.Test;public class RealPathTest { /** * Get the project path where the current class is located*/ @Test public void fun1() { File file = new File(this.getClass().getResource("/").getPath()); // D:/project/taotaoshop/src/blog-mybatis1/target/test-classes System.out.println(file); } /** * Get the absolute path to the current class*/ @Test public void fun2() { File file = new File(this.getClass().getResource("").getPath()); // D:/project/taotaoshop/src/blog-mybatis1/target/test-classes/com/ygh/blog/realpath System.out.println(file); } /** * Get the project path where the current class is located. Both methods can be used * * @throws IOException */ @Test public void fun3() throws IOException { File file = new File(""); String path = file.getCanonicalPath(); // D:/project/taotaoshop/src/blog-mybatis1 System.out.println(path); // D:/project/taotaoshop/src/blog-mybatis1 System.out.println(System.getProperty("user.dir")); } /** * Get the path of the file below the current src*/ @Test public void fun4() { URL url = this.getClass().getClassLoader().getResource("jdbc.properties"); System.out.println(url); } /** * Get the file path below other source code packages*/ @Test public void fun5() { // Use this method to get the path URL url = this.getClass().getClassLoader().getResource("test2.txt"); // file:/D:/project/taotaoshop/src/blog-mybatis1/target/classes/test.txt System.out.println(url); } @Test public void fun6() throws Exception { URL url = this.getClass().getClassLoader().getResource("test2.txt"); System.out.println(url.getPath()); Properties properties = new Properties(); // Use this method to get the output stream corresponding to the file InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(inputStream); File file = new File(url.getPath()); System.out.println(properties.get("jdbc.driverClassName")); }}The following is the file path corresponding to the code
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.