Shun
Shun

Reputation: 105

FileNotFound while File is there

I am using getClassLoader().getResources to find the path for Jsoup to parse.

String path = JsoupDemo1.class.getClassLoader().getResource("student.xml").getPath();
Document document = Jsoup.parse(new File(path), "utf-8");
Elements names = document.getElementsByTag("name");
System.out.println(names.size());

My student.xml has been placed under the src folder in my module "day11_xml" and this code snippet comes from the class JsoupDemo1 in the package cn.itcast.xml.jsoup under the same module of "day11_xml". The error messages reads as follows:

java.io.FileNotFoundException:/Users/dingshun/Downloads/New%20Java%20Projects/demo/out/production/day11_xml/student.xml (No such file or directory)

I don't get it, as I can find the exact file in the given path. I'm confused, but could you guys help me out? Also, I'm new to both Java programming and this forum and if this question sounds silly or my question format is not right, please let me know.

Upvotes: 0

Views: 80

Answers (2)

Shun
Shun

Reputation: 105

Actually, it turned out that Jsoup could not find my file because the path name "New%20Java%20Projects" has spaces between them. When I reload the file in a folder which has no spaces in its name, it works out just fine. So it can parse xml using parse​(File in, String charsetName) method. It seems it cannot parse path name which has spaces in it.

Upvotes: 0

matt
matt

Reputation: 12346

What you're doing looks good. Maybe use the stream version JSoup.parse.

URL url = JsoupDemo1.class.getClassLoader().getResource("student.xml");  
InputStream stream = JsoupDemo1.class.getClassLoader().getResourceAsStream("student.xml");
document = Jsoup.parse(stream, "utf-8", url.toURI()toString());

The documentation linked seems to imply it will work with html not xml, so maybe you need to use the other argument which provides a parser?

Upvotes: 1

Related Questions