java-网络文件下载器

来源:互联网 发布:python黑帽子 百度云 编辑:程序博客网 时间:2024/05/16 10:37

今天是2017.5.25,下午在实验室没事干,想起来了写博客,就把我之前写的一个网络文件下载器放上来吧,程序界面风格美观友好,人性化,如选择下载位置时配置了文件位置选择框,下载过程中使用了进度条myBar,如有问题请各位大佬多多指教!!!(逃
文件下载器运行初始界面如下:
这里写图片描述
下载过程的图片:
这里写图片描述
以下是程序代码:(程序代码我都写在一个java文件里,包括主要下载功能源码及界面的代码,直接把以下代码复制到一个java文件即可)

package pack1;import java.awt.BorderLayout;import java.awt.Color;import java.awt.EventQueue;import java.awt.FlowLayout;import java.awt.Image;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JProgressBar;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.ProgressMonitor;import javax.swing.ProgressMonitorInputStream;import javax.swing.SwingUtilities;import javax.swing.UIManager;import javax.swing.UIManager.LookAndFeelInfo;import javax.swing.UnsupportedLookAndFeelException;import javax.swing.event.DocumentEvent;import javax.swing.event.DocumentListener;public class 网络下载文件2 extends JPanelimplements DocumentListener{    static JTextArea it1,it2,it3;static JProgressBar myBar;    JButton button,button1,button2,button3;static JFrame frame;static File file;    static String[] s;static int k,q=0;JLabel label;static long length1=0,all=0;    //。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。神奇的分割线 。。。。。。。。。。。。。。。。。。。。。。。。。。。。    public static void getInternetResource(String savepath, String resurl, String fileName) throws MalformedURLException{        URL url = null;        HttpURLConnection con = null;        InputStream in = null;        FileOutputStream out = null;        try {            url = new URL(resurl);//建立http连接,得到连接对象            con = (HttpURLConnection) url.openConnection();                    in = con.getInputStream();//得到输入流            length1 = (int)con.getContentLength();//这个就是下载的文件(不单指文件)大小            System.out.println("文件长度为"+length1);            System.out.println(savepath);            file=new File(savepath+"//"+fileName);//得到文件                //System.out.println(it2.getText()+"//"+it3.getText());            out=new FileOutputStream(file);//得到文件输出流            int b=-1;            while((b=in.read())!=-1){                out.write(b);                double d=(100*file.length()/length1);//System.out.println(file.length());                       //myBar.setValue((int)d);//刷新进度条                    }            JOptionPane.showMessageDialog(frame, "文件下载完毕!","恭喜!",JOptionPane.ERROR_MESSAGE);            in.close();            out.close();            System.out.println("下载完毕!");        } catch (MalformedURLException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            try {                if (null != out)                    out.close();                if (null != in)                    in.close();            } catch (IOException e) {                e.printStackTrace();            }        }        System.out.println("下载函数测试完成!!!");    }    //。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。神奇的分割线      网络下载文件2()    {        super(new FlowLayout());        label=new JLabel("下载文件的链接:");        label.setFont(new java.awt.Font("Dialog",1,20));label.setForeground(Color.black);        this.add(label);        it1=new JTextArea(1,45);        this.add(new JScrollPane(it1));        it1.getDocument().addDocumentListener(this);            label=new JLabel("             保存位置:                    ");        label.setFont(new java.awt.Font("Dialog",1,20));label.setForeground(Color.black);        this.add(label);        it2=new JTextArea(1,38);        this.add(new JScrollPane(it2));        it2.getDocument().addDocumentListener(this);        button2=new JButton("选择");        button2.setFont(new java.awt.Font("Dialog",1,18));        button2.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent arg0) {                //创建文件对话框,让用户选择保存的位置路径                JFileChooser chooser=new JFileChooser("D:\\");//创建对话框对象                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设定选择为文件夹                int r=chooser.showOpenDialog(frame);                if(r==JFileChooser.APPROVE_OPTION){                    it2.setText(chooser.getSelectedFile().getAbsolutePath());//得到选择的本地路径                }                                                                           }               });        this.add(button2);        label=new JLabel("   保存文件名:");        label.setFont(new java.awt.Font("Dialog",1,20));label.setForeground(Color.black);        this.add(label);        it3=new JTextArea(1,45);        this.add(new JScrollPane(it3));        it3.getDocument().addDocumentListener(this);        button=new JButton("  开始下载   ");        button1=new JButton("退出");        button.setFont(new java.awt.Font("Dialog",1,20));        button1.setFont(new java.awt.Font("Dialog",1,20));          button1.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent arg0) {                frame.dispose();                        }               });        //按钮事件监听处理器        button.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent arg0) {                String a=it1.getText(),b=it2.getText(),c=it3.getText();System.out.println("正在开始下载");                                            JFrame frame5=new JFrame();                frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                //设置内容区                frame5.setTitle("当前文件的下载进度");                frame5.setSize(750, 100);                frame5.setLocation(450, 350);                frame5.setVisible(true);                frame5.setResizable(false);                 myBar=new JProgressBar();                   myBar.setForeground(Color.RED);                myBar.setStringPainted(true);                myBar.setBackground(Color.PINK);                frame5.add(myBar);                          new Thread(){                    public void run(){                        try {                            getInternetResource(b, a, c);                        } catch (MalformedURLException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        }                    }                }.start();                //弹出对话框表示下载文件完毕                //frame5.dispose();//关闭进度条                //JOptionPane.showMessageDialog(frame, "文件下载完毕!","恭喜!",JOptionPane.ERROR_MESSAGE);                  }        });        //添加按钮        this.add(button);this.add(button1);        button3=new JButton("已下载文件");        button.setFont(new java.awt.Font("Dialog",1,20));        button3.setFont(new java.awt.Font("Dialog",1,20));              button3.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent arg0) {                                 //创建文件对话框,让用户选择保存的位置路径                JFileChooser chooser=new JFileChooser("D://");//创建对话框对象                //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设定选择为文件夹                int r=chooser.showOpenDialog(frame);                if(r==JFileChooser.APPROVE_OPTION){                    //it2.setText(chooser.getSelectedFile().getAbsolutePath());//得到选择的本地路径                    String name = chooser.getSelectedFile().getPath();                      System.out.println(name);                    File _file=new File(name);                    String s[]=name.split("\\.");int len=s.length;                    //若选择的文件是图片,格式为jpg,gif,png                    if(s[len-1].equals("jpg")||s[len-1].equals("png")||s[len-1].equals("gif")){                        System.out.println(s[len-1]);                        Image src;int w = 0; //得到源图宽                        int h=0; //得到源图长                        try {                            src = javax.imageio.ImageIO.read(_file);                            //获取图片分辨率来设置窗口大小,使得图片适应窗口                             w=src.getWidth(null); //得到图宽                             h=src.getHeight(null); //得到图长                        } catch (IOException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        } //构造Image对象                        JFrame frame1 = new JFrame();                        JLabel label2=new JLabel();                        frame1.add(label2);                        frame1.setTitle("已下载文件内容");                        frame1.setSize(w, h);                        frame1.setLocation(500, 150);                        frame1.setVisible(true);                        frame1.setResizable(false);                             label2.setIcon(new ImageIcon(name));                        }                    //若选择的文件是文档,格式为doc,txt                    else if(s[len-1].equals("doc")||s[len-1].equals("txt"))                    {                        JFrame frame1 = new JFrame();                            JTextArea jt=new JTextArea(15,15);                            frame1.add(jt);                                                     frame1.setTitle("已下载文件内容");                            frame1.setSize(500, 250);                            frame1.setLocation(500, 150);                            frame1.setVisible(true);                            frame1.setResizable(false);                             try {                            FileReader f=new FileReader(name);                            BufferedReader br=new BufferedReader(f);                            String ss=null;                            int i=0;                            try {                                while((ss=br.readLine())!=null)                                {                                    i++;                                    jt.append(ss+"\n");                                }                            } catch (IOException e) {                                // TODO Auto-generated catch block                                e.printStackTrace();                            }                                               } catch (FileNotFoundException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        }                                           }                               }                                       }               });        this.add(button3);    }    //文本区监听处理    public void changedUpdate(DocumentEvent e) {        }    public void insertUpdate(DocumentEvent e) {     }    public void removeUpdate(DocumentEvent e) {     }       public static void createAndShowGUI()    {        frame=new JFrame("网络文件下载器");        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        //设置内容区        网络下载文件2 wt=new 网络下载文件2();        frame.setContentPane(wt);        frame.setSize(650, 330);        frame.setLocation(500, 250);        frame.setVisible(true);        frame.setResizable(false);//不可移动            }       public static void main(String[] args) {        try        {            for(LookAndFeelInfo info:UIManager.getInstalledLookAndFeels()){            if("Nimbus".equals(info.getName())){                UIManager.setLookAndFeel(info.getClassName());  break;}        }}        catch(UnsupportedLookAndFeelException e){}        catch(ClassNotFoundException e){}        catch(InstantiationException e){}        catch(IllegalAccessException e){}        // TODO Auto-generated method stub        EventQueue.invokeLater(new Runnable(){            public void run(){            createAndShowGUI();                 }        });    }}
原创粉丝点击