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
511 views
in Technique[技术] by (71.8m points)

java - Unable to load xml file from a absolute path

There is a maven project A. Once I do mvn clean install, the project builds and the jar is available at my local repository ie c: epositorycomstackoverflowAA.jar

A.jar contains couple of classes and xml files used by these classes

From another maven project I am invoking one of the methods in the class which uses one XML file.

Code is:

public File xmlFilder(String xmlAbsolutePath) {
  File f = new File(xmlAbsolutePath);
  return f;
}

The second project is located in my D drive. On getting the absolute path, I am getting as comstackoverflowA esp.xml which is the correct absolute path.

But If I add the following code at line 3 , I am getting as follows:

public File xmlFilder(String xmlAbsolutePath) {

  File f = new File(xmlAbsolutePath);

  System.out.println("AbsolutePath----"+f.getAbsolutePath());  ---> D:comstackoverflowA
esp.xml

  System.out.println("getPath------------"+f.getPath());       ---> comstackoverflowA
esp.xml 

  System.out.println("exists--------------"+f.exists());       ----> false

return f;

}

Can anyone please let me know where I am going wrong. Why it is not picking the xml from the repository which is present in C drive.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If the A class (that is bundled in your A.jar) wants to load the xml from the jar and it tries to access it in the way shown in your first code example then it does not access p.xml inside your jar. It accesses the file at that location.

It is easy to test if this is your case. After your jar is created, temporarily delete p.xml from the file system and run A class. It will fail to load it.

When a class needs to load a resource that is bundled in a jar then it does not use File but the classloader.

From the names you provide, I assume that your class A is in package: com.stackoverflow.A The xml file is in the package com.stackoverflow.A.res

All the approaches below will load a stream with your xml

InputStream is = null;

// Using class - relative to the class location because path does not start with "/"
is = SimpleWriter.class.getResourceAsStream("res/p.xml");

// Using class - absolute path because path starts with "/"
is = SimpleWriter.class.getResourceAsStream("/com/stackoverflow/A/res/p.xml");

// Using classloader - path is *always* absolute. Note that leading "/" is missing
is = SimpleWriter.class.getClassLoader().getResourceAsStream("com/stackoverflow/A/res/p.xml");

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

...