欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 实现局域网文件传输的实例

程序员文章站 2024-02-13 10:03:58
java 实现局域网文件传输的实例            本文主要实现...

java 实现局域网文件传输的实例

           本文主要实现局域网文件传输的实例,对java 的tcp知识,文件读写,socket等知识的理解应用,很好的实例,大家参考下,

实现代码:

clientfile.java

/**
 * 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com
 * @author 小沫
 */
 package com.tcp.file;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.socket;
import java.net.unknownhostexception;

import javax.swing.jprogressbar;

public class clientfile extends thread {

  private static string ip;
  private static int port;
  private string filepath;
  private long size;
  private jprogressbar jprogressbar;
  public clientfile(string ip, int port, string filepath, jprogressbar jprogressbar) {
    this.ip = ip;
    this.port = port;
    this.filepath = filepath;
    this.jprogressbar = jprogressbar;
  }
  public void run() {
    try {
      socket socket = new socket(ip, port);
      inputstream input = socket.getinputstream();
      outputstream output = socket.getoutputstream();

      file file = new file(filepath);
      // 第一次传输文件名字and文件的大小
      string str1 = file.getname() + "\t" + file.length();
      output.write(str1.getbytes());
      output.flush();
      byte[] b = new byte[100];
      int len = input.read(b);
      string s = new string(b, 0, len);
      // 如果服务器传输过来的是ok那么就开始传输字节
      if (s.equalsignorecase("ok")) {
        long size = 0;
        jprogressbar.setmaximum((int) (file.length() / 10000));// 设置进度条最大值
        fileinputstream fin = new fileinputstream(file);
        byte[] b1 = new byte[1024 * 1024 * 2];
        while (fin.available() != 0) {
          len = fin.read(b1);
          output.write(b1, 0, len);
          output.flush();
          size += len;
          jprogressbar.setvalue((int) (size / 10000));
        }
        if (fin.available() == 0) {
          javax.swing.joptionpane.showmessagedialog(null, "传输完毕!即将推出......");
          try {
            thread.sleep(1500);
            system.exit(0);
          } catch (interruptedexception e) {
            e.printstacktrace();
          }
        }
        output.close();
        fin.close();
        socket.close();
      } else {
        // 传输的不是ok那么就弹出个信息框对方拒绝
        javax.swing.joptionpane.showmessagedialog(null, "对方拒绝接收此数据!");
      }
    } catch (ioexception e) {
      javax.swing.joptionpane.showmessagedialog(null, "ioexception");
    }
  }

}

serverfile.java

/**
 * 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com
 * @author 小沫
 */
 package com.tcp.file;

import java.io.*;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.inetaddress;
import java.net.serversocket;
import java.net.socket;

import javax.swing.jfilechooser;
import javax.swing.joptionpane;
import javax.swing.jprogressbar;

public class serverfile extends thread {

  private socket socket;
  private jprogressbar jprogressbars;

  public serverfile(socket socket, jprogressbar jprogressbars) {
    this.socket = socket;
    this.jprogressbars = jprogressbars;
  }

  public void run() {
    try {
      inputstream input = socket.getinputstream();
      outputstream output = socket.getoutputstream();

      byte[] b = new byte[100];
      int len = input.read(b);
      string ss = new string(b, 0, len);
      string[] str1 = ss.split("\t");// 把接收到的信息按制表符拆分
      string filename = str1[0];// 起始位文件名称
      string filesize = str1[1];// 下标1位文件的大小
      long size = long.parselong(filesize);

      inetaddress ip = socket.getinetaddress();// 得到发送端的ip
      int port = socket.getport();// 得到发送端的端口

      long s = size / 1024 / 1024;
      string name = " m";
      if (s < 1) {
        s = (size / 1024);
        name = " k";
      } else if (s > 1024) {
        float s1 = size / 1024 / 1024;
        s = (size / 1024 / 1024 / 1024);
        name = " g多";
      }
      // 弹出确认款,显示对方的ip端口以及文件的名称和大小是否需要接收
      int i = joptionpane.showconfirmdialog(null,
          "来自: " + ip + ":" + port + "\n文件名称: " + filename + "\n文件大小: " + s + name);

      // 如果点击确认
      if (i == joptionpane.ok_option) {
        // 那么传输ok给发送端示意可以接收
        output.write("ok".getbytes());
        output.flush();
        jfilechooser jf = new jfilechooser();
        // 存储到本地路径的夹子
        jf.setfileselectionmode(jfilechooser.directories_only);
        jf.showopendialog(null);
        jprogressbars.setmaximum((int) (size / 10000));
        fileoutputstream fout = new fileoutputstream(new file(jf.getselectedfile(), filename));
        b = new byte[1024 * 1024 * 2];
        long size1 = 0;
        while ((len = input.read(b)) != -1) {
          fout.write(b, 0, len);
          size1 += len;
          jprogressbars.setvalue((int) (size1 / 10000));
        }
        fout.close();
        input.close();
        socket.close();

      } else {
        // 否不接收此文件
        output.write("no".getbytes());
        output.flush();
      }
    } catch (ioexception e) {
      javax.swing.joptionpane.showmessagedialog(null, "ioexception");
    }

  }
  private static serversocket server = null;
  // 启动服务器
  public static void openserver(int port, jprogressbar jprogressbar) throws exception {
    new thread() {
      public void run() {
        try {
          if (server != null && !server.isclosed()) {
            server.close();
          }
          server = new serversocket(port);
          new serverfile(server.accept(), jprogressbar).start();
        } catch (ioexception e) {
          javax.swing.joptionpane.showmessagedialog(null, "ioexception");
        }
      }
    }.start();
  }

  // 关闭服务器
  public static void closeserver() {
    try {
      server.close();
    } catch (ioexception e) {
      javax.swing.joptionpane.showmessagedialog(null, "ioexception");
    }
  }

}

socketfilejframe.java

/**
 * 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com
 * @author 小沫
 */
 package com.tcp.file;

import java.awt.borderlayout;
import java.awt.dimension;
import java.awt.eventqueue;
import java.awt.image;
import java.awt.toolkit;

import javax.swing.jframe;
import javax.swing.jpanel;
import javax.swing.border.emptyborder;
import java.awt.color;
import javax.swing.jtabbedpane;
import java.awt.panel;
import javax.swing.border.titledborder;
import javax.swing.uimanager;
import javax.swing.border.compoundborder;
import javax.swing.jlabel;
import java.awt.font;
import javax.swing.jtextfield;
import javax.swing.jtogglebutton;
import javax.swing.jprogressbar;
import javax.swing.jbutton;
import javax.swing.jfilechooser;
import javax.swing.event.ancestorlistener;
import javax.swing.event.ancestorevent;
import java.awt.event.actionlistener;
import java.io.ioexception;
import java.awt.event.actionevent;

public class socketfilejframe extends jframe {

  private jpanel contentpane;
  private jtextfield textfield;
  private jtextfield textfield_1;
  private jtextfield textfield_2;
  private jtextfield textfield_3;
  private jprogressbar progressbar_2;

  /**
   * launch the application.
   */
  public static void main(string[] args) {
    eventqueue.invokelater(new runnable() {
      public void run() {
        try {
          socketfilejframe frame = new socketfilejframe();
          frame.setvisible(true);
        } catch (exception e) {
          e.printstacktrace();
        }
      }
    });
  }

  /**
   * create the frame.
   */
  public socketfilejframe() {
    seticonimage(toolkit.getdefaulttoolkit()
        .getimage(socketfilejframe.class.getresource("/javax/swing/plaf/metal/icons/ocean/newfolder.gif")));
    setforeground(color.white);

    setresizable(false);
    settitle("局域网文件传输 v1.0");
    setdefaultcloseoperation(jframe.exit_on_close);
    int width = toolkit.getdefaulttoolkit().getscreensize().width;//获取分辨率宽
    int heiht = toolkit.getdefaulttoolkit().getscreensize().height;//获取分辨率高

    //分辨率宽高减去软件的宽高除以2把软件居中显示
    setbounds((width - 747) / 2, (heiht - 448) / 2, 738, 472);
    contentpane = new jpanel();
    contentpane.setbackground(color.white);
    contentpane.setborder(new emptyborder(5, 5, 5, 5));
    setcontentpane(contentpane);
    contentpane.setlayout(null);

    jpanel panel_1 = new jpanel();
    panel_1.settooltiptext("");
    panel_1.setborder(new titledborder(uimanager.getborder("titledborder.border"),
        "\u6587\u4ef6\u63a5\u6536\u670d\u52a1\u5668", titledborder.leading, titledborder.top, null,
        new color(0, 0, 0)));
    panel_1.setbackground(color.white);
    panel_1.setbounds(39, 28, 652, 119);
    contentpane.add(panel_1);
    panel_1.setlayout(null);

    jlabel label = new jlabel("\u7aef\u53e3:");
    label.setfont(new font("新宋体", font.plain, 22));
    label.setbounds(26, 31, 66, 35);
    panel_1.add(label);

    //端口文本框
    textfield = new jtextfield();
    textfield.setfont(new font("宋体", font.plain, 19));
    textfield.settext("8080");
    textfield.setbounds(89, 36, 126, 26);
    panel_1.add(textfield);
    textfield.setcolumns(10);

    //服务器关闭启动的按钮
    jtogglebutton tglbtnnewtogglebutton = new jtogglebutton("\u542f\u52a8\u670d\u52a1\u5668");
    tglbtnnewtogglebutton.addactionlistener(new actionlistener() {
      public void actionperformed(actionevent e) {

        if (tglbtnnewtogglebutton.isselected()) {
          //如果是按下显示关闭服务器
          tglbtnnewtogglebutton.settext("关闭服务器");
          textfield.setenabled(false);//按下之后 端口文本框要设置不能写入
          try {
            //启动服务器
            serverfile.openserver(integer.parseint(textfield.gettext())
                , progressbar_2);
          } catch (exception e1) {
            javax.swing.joptionpane.showmessagedialog(null, "exception");
          }
        } else {
          //否启动服务器
          tglbtnnewtogglebutton.settext("启动服务器");
          textfield.setenabled(true);////弹起之后 端口文本框要设置可写状态
          serverfile.closeserver();//关闭服务器
        }

      }
    });
    tglbtnnewtogglebutton.setfont(new font("微软雅黑 light", font.plain, 19));
    tglbtnnewtogglebutton.setbackground(color.white);
    tglbtnnewtogglebutton.setforeground(color.dark_gray);
    tglbtnnewtogglebutton.setbounds(345, 34, 138, 28);
    panel_1.add(tglbtnnewtogglebutton);

    //文件接收端的进度条
    progressbar_2 = new jprogressbar();
    progressbar_2.setbackground(color.white);
    progressbar_2.setforeground(new color(255, 218, 185));
    progressbar_2.setstringpainted(true);
    progressbar_2.setbounds(460, 101, 190, 14);
    panel_1.add(progressbar_2);

    jpanel panel_2 = new jpanel();
    panel_2.settooltiptext("");
    panel_2.setborder(new titledborder(uimanager.getborder("titledborder.border"), "\u6587\u4ef6\u4f20\u8f93\u7aef",
        titledborder.leading, titledborder.top, null, new color(0, 0, 0)));
    panel_2.setbackground(color.white);
    panel_2.setbounds(39, 191, 652, 202);
    contentpane.add(panel_2);
    panel_2.setlayout(null);

    //文件传输端的进度条
    jprogressbar progressbar_1 = new jprogressbar();
    progressbar_1.setfont(new font("宋体", font.plain, 18));
    progressbar_1.setstringpainted(true);
    progressbar_1.setforeground(new color(240, 128, 128));
    progressbar_1.setbackground(color.white);
    progressbar_1.setbounds(96, 169, 472, 20);
    panel_2.add(progressbar_1);

    jlabel lblip = new jlabel("ip\u5730\u5740:");
    lblip.setfont(new font("微软雅黑 light", font.plain, 20));
    lblip.setbounds(26, 44, 70, 27);
    panel_2.add(lblip);

    //ip地址文本框
    textfield_1 = new jtextfield();
    textfield_1.settext("127.0.0.1");
    textfield_1.setfont(new font("新宋体", font.plain, 20));
    textfield_1.setbounds(96, 44, 184, 30);
    panel_2.add(textfield_1);
    textfield_1.setcolumns(10);

    jlabel label_1 = new jlabel("\u7aef\u53e3:");
    label_1.setfont(new font("微软雅黑 light", font.plain, 20));
    label_1.setbounds(308, 42, 80, 30);
    panel_2.add(label_1);

    //端口文本框
    textfield_2 = new jtextfield();
    textfield_2.settext("8080");
    textfield_2.setfont(new font("新宋体", font.plain, 20));
    textfield_2.setcolumns(10);
    textfield_2.setbounds(359, 44, 80, 30);
    panel_2.add(textfield_2);

    //打开本地路径的按钮
    jbutton button = new jbutton("...");
    button.addactionlistener(new actionlistener() {
      public void actionperformed(actionevent e) {
        jfilechooser jf = new jfilechooser();
        jf.setfileselectionmode(jfilechooser.files_only);
        jf.showopendialog(socketfilejframe.this);
        textfield_3.settext(jf.getselectedfile().getpath());
      }
    });
    button.setbackground(color.white);
    button.setbounds(533, 51, 35, 20);
    panel_2.add(button);

    jlabel label_2 = new jlabel("\u8def\u5f84:");
    label_2.setfont(new font("微软雅黑 light", font.plain, 15));
    label_2.setbounds(489, 50, 44, 18);
    panel_2.add(label_2);

    //显示文件路径框
    textfield_3 = new jtextfield();
    textfield_3.setenabled(false);
    textfield_3.setfont(new font("微软雅黑 light", font.plain, 20));
    textfield_3.setbounds(96, 100, 343, 38);
    panel_2.add(textfield_3);
    textfield_3.setcolumns(10);

    jlabel lblnewlabel = new jlabel("\u6587\u4ef6:");
    lblnewlabel.setfont(new font("等线 light", font.plain, 25));
    lblnewlabel.setbounds(33, 97, 56, 38);
    panel_2.add(lblnewlabel);
    //确定按钮
    jbutton button_1 = new jbutton("\u786e\u5b9a");
    button_1.addactionlistener(new actionlistener() {
      public void actionperformed(actionevent e) {

        clientfile client = new clientfile(
            textfield_1.gettext(), integer.parseint(textfield_2.gettext()), 
            textfield_3.gettext(), progressbar_1);
        client.start();
      }
    });
    button_1.setforeground(new color(255, 255, 0));
    button_1.setbackground(new color(233, 150, 122));
    button_1.setfont(new font("微软雅黑 light", font.bold, 20));
    button_1.setbounds(475, 100, 91, 38);
    panel_2.add(button_1);
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!