共計 469 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以通過以下方法來獲取相對路徑文件:
- 使用相對路徑字符串直接創(chuàng)建 File 對象:
File file = new File(" 相對路徑 ");
- 使用相對路徑字符串構(gòu)建路徑對象,然后創(chuàng)建 File 對象:
Path path = Paths.get(" 相對路徑 ");
File file = path.toFile();
- 使用 ClassLoader 的 getResource 方法獲取相對路徑資源:
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource(" 相對路徑 ");
File file = new File(url.getPath());
- 使用當前類的 getResource 方法獲取相對路徑資源:
URL url = getClass().getResource(" 相對路徑 ");
File file = new File(url.getPath());
注意:在獲取相對路徑文件時,需要確保該文件在 classpath 中存在,否則會出現(xiàn)文件找不到的異常。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2024-05-27