# Path ###### tags: `Java` **class#getResource、class#getResourceAsStream** 使用class的方式,path 可接受絕對路徑、相對路徑 test5.class.getResource(path); test5.class.getResourceAsStream(path); 使用classLoader的方式,path 可接受絕對路徑 test5.class.getClassLoader().getResource(...); test5.class.getResourceAsStream().getResource(...); 然而getResource取得的是url,getResourceAsStream取得的是inputstream 因此開發階段跟包成jar、war階段getResource取得的路徑將會有些不同 getResource在jar、war會得到 D:xxxx/zzz.jar!/xxxx.xxx 而getResourceAsStream則依然可以取得目標檔案,在使用上要多注意 絕對路徑 /開頭 相對路徑 非/開頭 開發上建議方式 : 建立一個source folder 加入build path 將檔案歸類在source folder就不會有定位不到的問題 .classpath 範例 <classpath> <classpathentry kind="src" output="target/classes" path="src/main/java"> <attributes> <attribute name="optional" value="true"/> <attribute name="maven.pomderived" value="true"/> </attributes> </classpathentry> <classpathentry kind="src" output="target/test-classes" path="src/test/java"> <attributes> <attribute name="optional" value="true"/> <attribute name="maven.pomderived" value="true"/> </attributes> </classpathentry> <classpathentry kind="output" path="target/classes"/> </classpath> **File** new File("/");//該class所在的路徑最上層,在windows系統通常會是 c:\ or d:\ new File("");//project dir :d:\workspace\project
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up