本文實(shí)例為大家分享了java獲取不同路徑的方法,供大家參考,具體內(nèi)容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
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; /** * 獲取java下面的路徑的演示 */ import org.junit.Test; public class RealPathTest { /** * 獲取當(dāng)前類所在的工程路徑 */ @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); } /** * 獲取當(dāng)前類的絕對(duì)路徑 */ @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); } /** * 獲取當(dāng)前類所在的工程路徑,兩種方法皆可 * * @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" )); } /** * 獲取當(dāng)前src下面的文件的路徑 */ @Test public void fun4() { URL url = this .getClass().getClassLoader().getResource( "jdbc.properties" ); System.out.println(url); } /** * 獲取其他源碼包下面的文件路徑 */ @Test public void fun5() { // 使用這種方法可以獲取路徑 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(); // 使用這種方式可以獲取文件對(duì)應(yīng)的輸出流 InputStream inputStream = this .getClass().getClassLoader().getResourceAsStream( "jdbc.properties" ); properties.load(inputStream); File file = new File(url.getPath()); System.out.println(properties.get( "jdbc.driverClassName" )); } } |
下面賦上代碼對(duì)應(yīng)的文件路徑
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。