public class Main {
public static void main(String[] args) throws IOException {
System.out.println("----------Start------------------");
URL resource = Main.class.getClassLoader().getResource("test.txt");
System.out.println("resource: "+ resource.getPath());
File file = new File(resource.getPath());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
System.out.println("----------End------------------");
}
}
If I run this code from IDEA - all work
----------Start------------------
resource: /D:/javaHz/target/classes/test.txt
1
2
3
4
5
----------End------------------
Process finished with exit code 0
if I reun from java -jar - I get error
D:hz>java -jar hzTest-jar-with-dependencies.jar
----------Start------------------
resource: file:/D:/hz/hzTest-jar-with-dependencies.jar!/test.txt
Exception in thread "main" java.io.FileNotFoundException: D:hzfile:D:hzhzTe st-jar-with-dependencies.jar! est.txt (Syntax error in file name, folder name, or volume label)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at test.Main.main(Main.java:15)
I do not want use getResourceAsStream
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…