Java 如何使用JSoup根据JList的选择下载文件?
假设我有一个JList,代码如下:Java 如何使用JSoup根据JList的选择下载文件?,java,swing,jsoup,jlist,Java,Swing,Jsoup,Jlist,假设我有一个JList,代码如下: final JList<String> list = new JList<String>(model); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setToolTipText("Choose Version"); list.setBounds(10, 150, 414, 23); 最终JList列表=新JList(型号); list.setSel
final JList<String> list = new JList<String>(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setToolTipText("Choose Version");
list.setBounds(10, 150, 414, 23);
最终JList列表=新JList(型号);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setToolTipText(“选择版本”);
名单.挫折(1015041433);
我想制作一个功能,用户可以从网站上托管的此JList中选择一个文件,然后下载它。对于JList名称,我将使用托管文件的名称。(我想通过使用JSoup来实现这一点)
到目前为止,我有以下代码来显示名称:
DefaultListModel<String> model = new DefaultListModel<String>();
Document doc = null;
try {
doc = Jsoup.connect("https://mega.nz/fm/rqwQRKyR").get();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
for (Element file : doc.select("td.right td a")) {
model.addElement(file.attr("href"));
}
DefaultListModel=newDefaultListModel();
单据单据=空;
试一试{
doc=Jsoup.connect(“https://mega.nz/fm/rqwQRKyR).get();
}捕获(IOE3异常){
//TODO自动生成的捕捉块
e3.printStackTrace();
}
对于(元素文件:doc.select(“td.right td a”)){
model.addElement(file.attr(“href”);
}
在这个示例代码中,我从一个网站获取文件名,并将文件名添加到DefaultListModel。然后,我用这个模型创建了一个新的JList
但是,如何使我的程序能够下载使用JSoup选择的特定文件(基于文件名)?好了,在阅读了关于如何使用JSoup下载图像的问答之后,我最终得到了下面的代码。当您没有指定是希望将图像下载到内存中还是保存在本地文件中时,我实现了代码,使其能够同时执行这两种操作(即,它首先下载图像,然后提示用户保存图像(如果用户愿意)
导入java.awt.BorderLayout;
导入java.awt.CardLayout;
导入java.awt.Dimension;
导入java.awt.GridBagLayout;
导入java.awt.Window;
导入java.awt.image.buffereImage;
导入java.io.BufferedInputStream;
导入java.io.File;
导入java.io.IOException;
导入java.util.Objects;
导入javax.imageio.imageio;
导入javax.swing.DefaultListModel;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JDialog;
导入javax.swing.JFileChooser;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JList;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.JProgressBar;
导入javax.swing.JScrollPane;
导入javax.swing.ListSelectionModel;
导入org.jsoup.jsoup;
公共班机{
//一个JDialog,允许用户在本地保存下载的图像。。。
私有静态类ImageDialog扩展JDialog{
专用最终缓冲图像bimg;
private ImageDialog(最终窗口所有者,
最后的字符串标题,
最终JFileChooser sharedChooser,
最终缓冲区图像(bimg){
超级(所有者、标题、模态类型、应用程序和模态);
this.bimg=Objects.requirennull(bimg);
最终JLabel标签=新JLabel(新图像图标(bimg),JLabel.CENTER);
最终JScrollPane滚动=新JScrollPane(标签);
scroll.setPreferredSize(新维度(600600));
最终JList选项=新JList(ImageIO.getWritePerformatNames());
选项。设置选择模式(ListSelectionModel.单选);
最终JButton保存=新JButton(“保存”);
save.addActionListener(e->{
if(JOptionPane.OK_OPTION==JOptionPane.showConfirmDialog(ImageDialog.this,选项,“选择图像类型”,JOptionPane.OK_取消_选项)){
最终字符串imageFormat=options.getSelectedValue();
if(imageFormat==null)
showMessageDialog(ImageDialog.this,“您必须先选择图像类型!”);
else if(sharedChooser.showSaveDialog(ImageDialog.this)=JFileChooser.APPROVE\u选项){
最终文件imagePath=sharedChooser.getSelectedFile();
if(imagePath.exists())//我会避免覆盖文件。
showMessageDialog(ImageDialog.this,“您不能覆盖图像!请先手动删除它们。”,“Oups!”,JOptionPane.WARNING_消息);
否则{
试一试{
ImageIO.write(bimg、imageFormat、imagePath);
showMessageDialog(ImageDialog.this,“在\”“+imagePath+“\”、“\”、“确定”下成功保存了图像”,JOptionPane.INFORMATION\u消息);
}
捕获(最终iox异常iox){
iox.printStackTrace();
showMessageDialog(ImageDialog.this,“保存图像失败!”+iox,“错误!”,JOptionPane.Error\u消息);
}
}
}
}
});
最终JPanel内容=新JPanel(新BorderLayout());
添加(滚动、边框布局、居中);
内容。添加(保存,边框布局。页面结束);
super.setDefaultCloseOperation(JDialog.DISPOSE\u ON\u CLOSE);
super.getContentPane().add(内容);
super.pack();
super.setLocationRelativeTo(所有者);
}
}
公共静态void main(最终字符串[]args){
//这是填充模型的位置:
最终DefaultListModel=新DefaultListModel();
模型补遗(“https://i.stack.imgur.com/PUMHY.png");
模型补遗(“https://i.stack.imgur.com/PUMHY.png");
模型补遗(“https://i.stack.imgur.com/PUMHY.png");
模型补遗(“https://i.stack.imgur.com/PUMHY.png");
//列表创建和初始化:
最终JList列表=新JList(型号);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//列表的JScrollPane:
最终JScro
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import org.jsoup.Jsoup;
public class Main {
//A JDialog which allows the user to save the downloaded image locally...
private static class ImageDialog extends JDialog {
private final BufferedImage bimg;
private ImageDialog(final Window owner,
final String title,
final JFileChooser sharedChooser,
final BufferedImage bimg) {
super(owner, title, ModalityType.APPLICATION_MODAL);
this.bimg = Objects.requireNonNull(bimg);
final JLabel label = new JLabel(new ImageIcon(bimg), JLabel.CENTER);
final JScrollPane scroll = new JScrollPane(label);
scroll.setPreferredSize(new Dimension(600, 600));
final JList<String> options = new JList<>(ImageIO.getWriterFormatNames());
options.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JButton save = new JButton("Save");
save.addActionListener(e -> {
if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(ImageDialog.this, options, "Select image type", JOptionPane.OK_CANCEL_OPTION)) {
final String imageFormat = options.getSelectedValue();
if (imageFormat == null)
JOptionPane.showMessageDialog(ImageDialog.this, "You have to select an image type first!");
else if (sharedChooser.showSaveDialog(ImageDialog.this) == JFileChooser.APPROVE_OPTION) {
final File imagePath = sharedChooser.getSelectedFile();
if (imagePath.exists()) //I would avoid overwriting files.
JOptionPane.showMessageDialog(ImageDialog.this, "You cannot overwrite images! Delete them manually first.", "Oups!", JOptionPane.WARNING_MESSAGE);
else {
try {
ImageIO.write(bimg, imageFormat, imagePath);
JOptionPane.showMessageDialog(ImageDialog.this, "Saved image successfully under \"" + imagePath + "\".", "Ok", JOptionPane.INFORMATION_MESSAGE);
}
catch (final IOException iox) {
iox.printStackTrace();
JOptionPane.showMessageDialog(ImageDialog.this, "Failed to save image! " + iox, "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
}
});
final JPanel contents = new JPanel(new BorderLayout());
contents.add(scroll, BorderLayout.CENTER);
contents.add(save, BorderLayout.PAGE_END);
super.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
super.getContentPane().add(contents);
super.pack();
super.setLocationRelativeTo(owner);
}
}
public static void main(final String[] args) {
//This is where you fill the model:
final DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("https://i.stack.imgur.com/PUMHY.png");
model.addElement("https://i.stack.imgur.com/PUMHY.png");
model.addElement("https://i.stack.imgur.com/PUMHY.png");
model.addElement("https://i.stack.imgur.com/PUMHY.png");
//List creation and initialization:
final JList<String> list = new JList<>(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//JScrollPane for list:
final JScrollPane scroll = new JScrollPane(list);
scroll.setPreferredSize(new Dimension(400, 400));
final JFileChooser sharedChooser = new JFileChooser();
sharedChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
sharedChooser.setMultiSelectionEnabled(false);
final JProgressBar bar = new JProgressBar();
bar.setBorderPainted(false);
bar.setStringPainted(true);
bar.setString("Downloading, please wait...");
bar.setIndeterminate(true);
//Create an extra panel which will have the progress bar centered in it...
final JPanel centeredBar = new JPanel(new GridBagLayout());
centeredBar.add(bar);
final JButton button = new JButton("Download");
final JPanel contents = new JPanel(new BorderLayout());
contents.add(scroll, BorderLayout.CENTER);
contents.add(button, BorderLayout.PAGE_END);
//Creating the cards to add in the content pane of the jframe:
final String cardProgressBar = "PROGRESS_BAR",
cardList = "LIST";
final CardLayout cardl = new CardLayout();
final JPanel cards = new JPanel(cardl);
cards.add(contents, cardList);
cards.add(centeredBar, cardProgressBar);
cardl.show(cards, cardList);
final JFrame frame = new JFrame("JList for JSoup");
button.addActionListener(e -> {
cardl.show(cards, cardProgressBar);
new Thread(() -> {
final String imagePath = list.getSelectedValue();
if (imagePath == null)
JOptionPane.showMessageDialog(frame, "No image selected!");
else {
try {
//This is the actual downloading you requested:
try (final BufferedInputStream bis = Jsoup.connect(imagePath).ignoreContentType(true).execute().bodyStream()) {
final BufferedImage bimg = ImageIO.read(bis);
new ImageDialog(frame, imagePath, sharedChooser, bimg).setVisible(true);
}
}
catch (final IOException iox) {
iox.printStackTrace();
JOptionPane.showMessageDialog(frame, "Failed to download \"" + imagePath + "\"! " + iox);
}
finally {
cardl.show(cards, cardList);
}
}
}).start();
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(cards);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}