既然你通過Class
對象使用一個資源文件,路徑到資源必須是絕對的:
getClass().getResourceAsStream("/Subfolder/file.txt");
注意,這樣做你做的是一個壞主意,那就是,打開掃描儀資源,你沒有參考:
new Scanner(someInputStreamHere());
你沒有參考輸入流,因此你不能關閉它。
更重要的是,如果資源不存在,.getResource*()
返回null
;在這種情況下,你會得到一個NPE!
建議,如果你使用Java 6(使用番石榴的更緊密):
final URL url = getClass().getResource("/path/to/resource");
if (url == null) // Oops... Resource does not exist
barf();
final Closer closer = Closer.create();
final InputStream in;
final Scanner scanner;
try {
in = closer.register(url.openStream());
scanner = closer.register(new Scanner(in));
// do stuff
} catch (IOException e) {
throw closer.rethrow(e);
} finally {
closer.close();
}
如果使用Java 7中,只使用try-與資源聲明:
final URL url = getClass().getResource("/path/to/resource");
if (url == null) // Oops... Resource does not exist
barf();
final InputStream in;
final Scanner scanner;
try (
in = url.openStream();
scanner = new Scanner(in);
) {
// do stuff
} catch (IOException e) {
// deal with the exception if needed; or just declare it at the method level
}
來源
2013-06-30 16:57:02
fge
我不知道如果這是有幫助的 - 但我有時需要檢查我的代碼運行的位置,以找出相對路徑,所以我只需要執行'(new java.io.File(「。」)。getCanonicalPath()'。 – selig