编写一个下载程序。要求:
(1)一个文本文件里存储了要下载的文件地址(可以先搜集若干个Mp3文件的下载地址),每行一个。
(2)让用户选择含有下载地址的文件;
(3)在程序中读取地址,并开始下载(下载开始、结束、失败都要有提示);
(4)如有能力,请考虑如何使用多线程同时下载多个文件?要避免多个线程同时下载一个文件。编写一个网络程序,实现两个人的聊天功能。要求:
(1)客户端启动后,先允许用户设置服务器端IP、PORT,再开始建立连接;
(2)任何一方要退出,必须先向另外一方能够发送“bye”,收到方同时退出程序。

解决方案 »

  1.   

    (1)一个文本文件里存储了要下载的文件地址(可以先搜集若干个Mp3文件的下载地址),每行一个。
    假设这些地址你已经有了,并且储存在ArrayList里面
    ArrayList list;//地址
        BufferedWriter bw = null;
        try {
          bw = new BufferedWriter(new FileWriter("E:/a.txt"));
          for (int i = 0; i < list.size(); i++) {
            bw.write( (String) list.get(i));
            bw.write("\r\n");
          }
          bw.flush();
        }
        catch (IOException ex) {
        }finally{
          if(bw!=null){
            try {
              bw.close();
            }
            catch (IOException ex1) {
            }
          }
        }
    (2)让用户选择含有下载地址的文件;
    就是选择文件
    File f=null;
        JFileChooser fc=new JFileChooser();
        int res=fc.showOpenDialog(null);
        if(res==JOptionPane.OK_OPTION){
          f=fc.getSelectedFile();
        }else{
          return;
        }
        System.out.println(f);
    (3)在程序中读取地址,并开始下载(下载开始、结束、失败都要有提示);
    读取文件
    ArrayList list=new ArrayList();
        BufferedReader br = null;
        try {
          br = new BufferedReader(new FileReader("E:\\a.txt"));
          String str;
          while ( (str = br.readLine()) != null) {
            list.add(str);
          }
        }
        catch (IOException ex) {
        }finally{
          if(br!=null){
            try {
              br.close();
            }
            catch (IOException ex1) {
            }
          }
        }(4)如有能力,请考虑如何使用多线程同时下载多个文件?要避免多个线程同时下载一个文件。
    下载文件放到这里吧
     public void download(String path,String toPath){
        InputStream is = null; FileOutputStream fos = null;
        try {
          URL url = new URL(path);
          is = url.openStream();
          int size = is.available();
          byte buf[] = new byte[size];
          BufferedInputStream bis = new BufferedInputStream(is);
          bis.read(buf);
          fos = new FileOutputStream(toPath);
          BufferedOutputStream bos = new BufferedOutputStream(fos);
          bos.write(buf);
          bos.flush();
        }
        catch (Exception ex) {
        }finally{
          if(is!=null){
            try {
              is.close();
            }
            catch (IOException ex1) {
            }
          }
          if(fos!=null){
            try {
              fos.close();
            }
            catch (IOException ex2) {
            }
          }
        }
      }
    需要多线程下载,只需要把这个方法放到run里面去就可以了
    第一个问题我简单讲了,具体细节还要调整,你自己看看吧
    编写一个网络程序,实现两个人的聊天功能。要求:
    (1)客户端启动后,先允许用户设置服务器端IP、PORT,再开始建立连接;
    (2)任何一方要退出,必须先向另外一方能够发送“bye”,收到方同时退出程序。
      

  2.   

    BTW:上面的代码没有测试,只是写上.可能有bug,你自己调试一下看看有问题没