gpt4 book ai didi

java - 在 For 循环中从 LinkedList 中删除元素;备择方案?

转载 作者:行者123 更新时间:2023-12-02 09:04:26 25 4
gpt4 key购买 nike

我正在开发一个自动从网站下载视频的程序。每个链接都有一个视频链接,因此我抓取该链接,然后通过重定向来实际获取直接下载链接。无论如何,我无法从 LinkedList 中删除该元素;我试图做到这一点,以便在下载视频后,该元素被删除并移动到下一个元素(网站 URL)。目前,它给了我一个警告,说用 iterator().remove() 替换它,但是当我这样做时,它给了我另一个错误:“IllegalStateException”。我还必须知道要下载哪一集,以确定是否需要在节目中稍后跳过它(如果已经下载)。我尝试通过设置一个字段变量来实现这一点,但也没有太多运气,因为我使用的是 for 循环,而 for 循环使用局部变量。我不知道还能尝试什么,所以任何帮助将不胜感激!谢谢!

package com.trentmenard;
import org.jsoup.*;
import org.jsoup.nodes.*;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.LinkedList;

import static javax.swing.WindowConstants.EXIT_ON_CLOSE;

class WebsiteScraper {
private Document websiteConnection;
private String episodeName;
private String iFrameLink;
private String URLDownloadLink;
private String URL;
private static DecimalFormat decimalFormat = new DecimalFormat("#.##");

private LinkedList<String> episodeURLs = new LinkedList<>();
private int currentEpisodeDownloading;

WebsiteScraper(String URL) {
for(int i = 1; i < 25; i++){
episodeURLs.add("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + i + "-english-dubbed-watch-online/");
}
for(int x = 1; x < 25; x++){
connectToURL("https://swordartonlineepisode.com/sword-art-online-season-3-episode-" + x + "-english-dubbed-watch-online/");
episodeURLs.remove(x);
currentEpisodeDownloading = x;
getEpisodeName();
}
}

private void connectToURL(String URL) {
try{
websiteConnection = Jsoup.connect(URL).get();
System.out.println("Connection Successfully Established to: " + URL);
}catch (IOException e)
{e.printStackTrace();}

if(URL.equals(iFrameLink)){
getDownloadLink();
}
else if(URL.equals(URLDownloadLink)) {
getDirectDownloadLink();
}
}

private void getEpisodeName(){
Element h2 = websiteConnection.selectFirst("h2");
episodeName = h2.text();
System.out.println("Found Episode Name: " + episodeName);
getIFrameLink();
}

private void getIFrameLink(){
Element iFrame = websiteConnection.selectFirst("iframe");
iFrameLink = iFrame.attr("src");
System.out.println("Found iFrame Link: " + iFrameLink + " for: " + episodeName);
connectToURL(iFrameLink);
}

private void getDownloadLink() {
Element hiddenID = websiteConnection.getElementById("id");
String hiddenIDValue = hiddenID.attr("value");
URLDownloadLink = "https://www.vidstreaming.io/download?id=" + hiddenIDValue;
System.out.println("Found Download Link Using ID Value (" + hiddenIDValue + "): " + URLDownloadLink);
connectToURL(URLDownloadLink);
}

private void getDirectDownloadLink(){
Element downloadClass = websiteConnection.getElementsContainingOwnText("Download (orginalP - mp4)").first();
String directDownloadLink = downloadClass.attr("href");
System.out.println("Found Direct Download Link: " + directDownloadLink);
downloadEpisode(directDownloadLink, episodeName);
}

private void downloadEpisode(String URL, String episodeName) {
this.URL = URL;

float Percent = 0;
String downloadProgress = "0.00";

JFrame progressFrame = new JFrame();
JProgressBar progressBar = new JProgressBar(0, 100);

progressBar.setSize(100, 100);
progressBar.setValue(0);
progressBar.setStringPainted(true);

progressFrame.setTitle("Downloading: " + episodeName + " - " + Percent + "%");
progressFrame.add(progressBar);
progressFrame.setVisible(true);
progressFrame.setLayout(new FlowLayout());
progressFrame.setSize(575, 100);
progressFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);

JLabel percentComplete = new JLabel(downloadProgress + "% complete.");
progressFrame.add(percentComplete);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

File createFile = new File(episodeName + ".mp4");
if (createFile.exists() && !createFile.isDirectory()) {
System.out.println("File: " + episodeName + " Already Exists! Moving Onto Next URL.");
// TODO: 1/26/2020 FOR STATEMENT FOR MOVING ONTO NEXT URL.
}
try {
java.net.URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

System.out.println("Connection Successfully Established!");
System.out.println("Downloading File: " + episodeName);

int filesize = connection.getContentLength();
float totalDataRead = 0;
byte[] data = new byte[1024];
int i = 0;

java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(episodeName + ".mp4");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);

while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
Percent = (totalDataRead * 100) / filesize;
decimalFormat.setRoundingMode(RoundingMode.CEILING);
downloadProgress = decimalFormat.format(Percent);

progressFrame.setTitle("Downloading: " + episodeName);
progressBar.setValue((int) Percent);
percentComplete.setText(downloadProgress);
}
bout.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Connection Failed!");
}
}
}

最佳答案

Collection接口(interface)定义了一个方法removeIf(Predicate<? super T> predicate)顾名思义,删除所有满足 Predicate 的元素。您可以使用它来避免您的 IllegalStateException (虽然您没有显示堆栈跟踪,但我想根本原因是 ConcurrentModificationException )。

例如:

List<String> list = Arrays.asList("hello", "world", "abc");
list.removeIf(str -> str.length() == 5);

// list = {"abc"}

但是,就您而言,您正在调用 list.remove(x) ,其中xintList<String>上。由于您迭代 x ,我期望这段代码,即使你修复了 IllegalStateException当您尝试访问超出范围的索引时,将抛出另一个异常。

关于java - 在 For 循环中从 LinkedList 中删除元素;备择方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59925712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com