Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
175 views
Welcome To Ask or Share your Answers For Others

1 Answer

new File(resource.getPath()) won't work because file:/D:/hz/hzTest-jar-with-dependencies.jar!/test.txt isn't really a filesystem path.

Since the file is part of jar file (a zip archive in fact), there is no valid filesystem path that would point to it.

The standard way is to use getClassLoader().getResourceAsStream("test.txt");. You'll either have to modify your application so that it can read from classpath resources or URLs, or use getResourceAsStream() to copy the resource to a temporary file on filesystem and then point to it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...