我有一個抓取網頁的程式。我正在使用 JSoup 和 Selenium。要在 JSoup 請求中配置用戶代理,我有一個 userAgents.txt 檔案,其中包含用戶代理串列。在每次執行中,我都有一個讀取 .txt 檔案并回傳隨機用戶代理的方法。
該程式在 IntelliJ 中運行時按預期作業。
當我嘗試使用 .jar 構建 .jar 檔案時,就會出現問題mvn clean package。運行 .jar 檔案時,我得到一個FileNotFoundException,因為程式找不到該userAgents.txt檔案。
如果我洗掉此功能,并對用戶代理進行硬編碼,我就沒有問題。
該檔案當前位于src/main/resources. 執行 .jar 時,出現例外:
java.io.FileNotFoundException: ./src/main/resources/userAgents.txt (沒有這樣的檔案或目錄)
我嘗試使用 maven-resources-plugin 將檔案復制到目標檔案夾中:
<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 檔案中,這樣當我運行它時,程式會從該檔案中讀取并且不回傳任何例外?
uj5u.com熱心網友回復:
您可以getResourceAsStream改用,如下所示:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
{...}
InputStream inStream = YourClass.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);
}
不必<resources>在 pom.xml 檔案中指定。您只需在運行maven package.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/522190.html
標籤:爪哇行家网页抓取汤
上一篇:如何打開Emmet代碼縮寫建議?
下一篇:抓取資料并收集所有href值
