文件下载

来源:互联网 发布:天猫网络培训 编辑:程序博客网 时间:2024/06/06 14:17

web文件下载

package download.util;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.net.ssl.HttpsURLConnection;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JTextField;public class DownLoadJFrame extends JFrame {// 声明组件private JLabel downLoadJLable;private JTextField downLoadJTextField;private JButton downLoadJButton;public DownLoadJFrame() {// 设置标题super("下载工具");// 设置大小this.setSize(450, 300);// 设置居中显示this.setLocationRelativeTo(null);// 设置窗体关闭即退出程序this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 获取容器对象Container c = this.getContentPane();// 设置容器面板布局为nullc.setLayout(null);// 实例化组件downLoadJLable = new JLabel("下载的地址:");downLoadJTextField = new JTextField("http://172.22.64.103:8080/day01/images/3.jpg");downLoadJButton = new JButton("下载");// 设置组件的位置downLoadJLable.setBounds(10, 20, 80, 30);downLoadJTextField.setBounds(95, 20, 280, 30);downLoadJButton.setBounds(120, 100, 100, 30);// 添加到面板中c.add(downLoadJLable);c.add(downLoadJTextField);c.add(downLoadJButton);// 添加点击事件downLoadJButton.addActionListener(new MyActionLis());// 设置窗体可见this.setVisible(true);}public static void main(String[] args) {new DownLoadJFrame();}/** * 内部类 *  * @author XinFei *  */class MyActionLis implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {downLoadJButton.setEnabled(false);System.out.println("bbbb");try {// 创建连接的URL对象URL url = new URL(downLoadJTextField.getText());// 打开连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();// 获取输入流对象InputStream is = urlConn.getInputStream();// 写出的文件File file = new File("F:\\ss.jpg");// 输出流对象OutputStream os = new FileOutputStream(file);int len = 0;byte buffer[] = new byte[1023];while ((len = is.read(buffer)) != -1) {os.write(buffer, 0, len);}is.close();os.flush();os.close();} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}}}


0 0