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, "下载完毕"); } }
JAVA下载器
时间: 2024-10-05 16:39:30