.jar文件中没有包含Maven Package:.txt



我有一个程序可以抓取网页。我使用的是JSoup和Selenium。为了在JSoup请求中配置用户代理,我有一个userAgents.txt文件,其中包含一个用户代理列表。在每次执行中,我都有一个方法来读取.txt文件,并返回一个随机的用户代理。

该程序在IntelliJ中运行时工作正常。

当我尝试使用mvn clean package构建.jar文件时,就会出现问题。当运行.jar文件时,我得到了一个FileNotFoundException,因为程序找不到userAgents.txt文件。

如果我删除此功能,并硬编码用户代理,我就没有问题了。

文件当前位于src/main/resources中。当执行.jar时,我得到一个异常:

java.io.FileNotFoundException:./src/main/resources/userAgents.txt(否这样的文件或目录(

我尝试了maven资源插件将文件复制到目标文件夹:

<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>package</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/extra-resources</outputDirectory>
<includeEmptyDirs>true</includeEmptyDirs>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>

即使更改程序内部的路径(从target/extra-resources打开文件(,错误仍然存在。

我还添加了这个<resources>,但一无所获:

<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.txt</include>
<include>**/*.csv</include>
</includes>
</resource>
</resources>

在程序内部,我正在使用读取文件

String filePath = "./src/main/resources/userAgents.txt";
File extUserAgentLst = new File(filePath);
Scanner usrAgentReader = new Scanner(extUserAgentLst);

所以,我的问题是:

  • 如何确保userAgents.txt文件在.jar文件中,以便在运行它时,程序从该文件中读取并且不会返回任何异常

您可以使用getResourceAsStream,如下所示:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public class MyClass {
public static void main(String[] args) {
InputStream inStream = MyClass.class.getClassLoader().getResourceAsStream("userAgents.txt");
if (inStream != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
String usersTxt = reader.lines().collect(Collectors.joining());
System.out.println(usersTxt);
}
}
}

不需要在pom.xml文件中指定标记<resources>。在运行mvn package命令构建项目之前,您只需要将文件放置在src/main/resources中。

最新更新