java.io.FileNotFoundException 使用 Jsoup 时
java.io.FileNotFoundException when using Jsoup
我试图从我当前的项目中读取一个 .html 资源(并解析它),如下所示:
leaflet.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
当我尝试使用 Jsoup
运行 以下代码时:
import java.io.File;
import org.jsoup.nodes.Document;
import org.jsoup.Jsoup;
// some code
File input = new File("\src\main\resources\leafletfile.html");
System.out.print(input.getAbsolutePath()); // This works
//Exception is here:
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
我收到以下异常:
java.io.FileNotFoundException: \src\main\resources\leafletfile.html (The system cannot find the path specified)
有人可以指教吗?提前致谢!
要从资源中获取文件,您应该使用不同的方法:
new File(getClass().getClassLoader().getResource("leaflet.html").getFile());
您的方法正在文件系统中查找您作为参数提供的路径。你的路径不是绝对路径,而是jar的相对路径。
如果这是在静态方法中,您应该在 getClass()
之前提供 class 名称,例如:
new File(ClassName.class.getClassLoader().getResource("leaflet.html").getFile());
这是因为 getClass()
单独解析为 this.getClass()
,但静态上下文中没有 this
。
记得在将文件添加到资源后进行清理和构建。
我试图从我当前的项目中读取一个 .html 资源(并解析它),如下所示:
leaflet.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>TODO write content</div>
</body>
</html>
当我尝试使用 Jsoup
运行 以下代码时:
import java.io.File;
import org.jsoup.nodes.Document;
import org.jsoup.Jsoup;
// some code
File input = new File("\src\main\resources\leafletfile.html");
System.out.print(input.getAbsolutePath()); // This works
//Exception is here:
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
我收到以下异常:
java.io.FileNotFoundException: \src\main\resources\leafletfile.html (The system cannot find the path specified)
有人可以指教吗?提前致谢!
要从资源中获取文件,您应该使用不同的方法:
new File(getClass().getClassLoader().getResource("leaflet.html").getFile());
您的方法正在文件系统中查找您作为参数提供的路径。你的路径不是绝对路径,而是jar的相对路径。
如果这是在静态方法中,您应该在 getClass()
之前提供 class 名称,例如:
new File(ClassName.class.getClassLoader().getResource("leaflet.html").getFile());
这是因为 getClass()
单独解析为 this.getClass()
,但静态上下文中没有 this
。
记得在将文件添加到资源后进行清理和构建。