所以我做了這個
package main;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class Test {
private Test() {
Class<?> c = this.getClass();
ClassLoader cl = c.getClassLoader();
InputStream[] iss = new InputStream[8];
URL[] urls = new URL[8];
iss[0] = c.getResourceAsStream("/resources/txtFile.txt");
iss[1] = c.getResourceAsStream("resources/txtFile.txt");
iss[2] = c.getResourceAsStream("/txtFile.txt");
iss[3] = c.getResourceAsStream("txtFile.txt");
iss[4] = cl.getResourceAsStream("/resources/txtFile.txt");
iss[5] = cl.getResourceAsStream("resources/txtFile.txt");
iss[6] = cl.getResourceAsStream("/txtFile.txt");
iss[7] = cl.getResourceAsStream("txtFile.txt");
urls[0] = c.getResource("/resources/txtFile.txt");
urls[1] = c.getResource("resources/txtFile.txt");
urls[2] = c.getResource("/txtFile.txt");
urls[3] = c.getResource("txtFile.txt");
urls[4] = cl.getResource("/resources/txtFile.txt");
urls[5] = cl.getResource("resources/txtFile.txt");
urls[6] = cl.getResource("/txtFile.txt");
urls[7] = cl.getResource("txtFile.txt");
for (int i = 0; i < 8; i++)
System.out.println("iss[" + i + "] is "
+ String.valueOf(iss[i] == null));
for (int i = 0; i < 8; i++)
System.out.println("url[" + i + "] is "
+ String.valueOf(urls[i] == null));
int read;
try {
while ((read = iss[0].read()) != -1)
System.out.print((char) read);
} catch (IOException e) {
}
}
public static final void main(String[] args) {
new Test();
}
}
Outprint:
iss[0] is false
iss[1] is true
iss[2] is true
iss[3] is true
iss[4] is true
iss[5] is false
iss[6] is true
iss[7] is true
url[0] is false
url[1] is true
url[2] is true
url[3] is true
url[4] is true
url[5] is false
url[6] is true
url[7] is true
This is sample text.
結論:它工作時,我用getClass().getResource("/resources/txtFile.txt")
或getClass().getClassLoader().getResource("resources/txtFile.txt")
(getResourceAsStream()
也適用)。
如果你解壓縮jar文件,你會看到該文件嗎? – roby
是的,該文件是在資源文件夾內的瓶子 – durchstarter
資源或資源?你的代碼段說資源 – roby