首页 > 代码库 > JAVA下载器
JAVA下载器
package com.longneo.downloader;import java.awt.*;import java.awt.event.*;import java.io.FileOutputStream;import java.io.InputStream;import java.net.URL;import java.net.URLConnection;import javax.swing.*;public class Downloader { private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); private final JFrame fm = new JFrame(); private final JPanel panel = new JPanel(); private final JLabel label1 = new JLabel("网络资源的下载 "); private final JLabel label2 = new JLabel("网络资源地址:"); private final Al al = new Al(); JButton StartButton = new JButton("开始下载"); JButton resetButton = new JButton("清空"); JButton exitButton = new JButton("退出"); JTextField urlField = new JTextField(20); public void init(){ panel.setLayout(new FlowLayout()); label1.setFont(new Font("雅黑", Font.BOLD, 15)); panel.add(label1); panel.add(label2); panel.add(urlField); panel.add(StartButton); panel.add(resetButton); panel.add(exitButton); fm.setContentPane(panel); StartButton.addActionListener(al); resetButton.addActionListener(al); exitButton.addActionListener(al); fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fm.setSize(400, 200); fm.setResizable(true); fm.setLocation((screenSize.width-fm.getWidth())/2,(screenSize.height-fm.getHeight())/2); fm.setVisible(true); } public class Al implements ActionListener{ @Override public void actionPerformed(ActionEvent e){ if(e.getSource() == StartButton){ if("".equals(urlField.getText())){ JOptionPane.showMessageDialog(fm, "请输入资源地址"); return; } String url = urlField.getText(); try{ download(url); }catch(Exception e1){ JOptionPane.showMessageDialog(fm, "地址有误,请检查,谢谢!"); e1.printStackTrace(); } }else if(e.getSource() == resetButton){ urlField.setText(""); }else{ System.exit(0); } } } public void download(String address) throws Exception{ URL url = new URL(address); URLConnection urlcon = url.openConnection(); urlcon.connect(); InputStream in = urlcon.getInputStream(); String filePath = url.getFile(); int pos = filePath.lastIndexOf("/"); String fileName = filePath.substring(pos + 1); FileOutputStream out = new FileOutputStream("F:\\" + fileName); byte[] bytes = new byte[1024]; int len = in.read(); while(len != -1){ out.write(bytes, 0, len); len = in.read(); } out.close(); in.close(); JOptionPane.showMessageDialog(fm, "下载完毕"); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。