Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

maven - Java read file from resources from jar

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...