java 实现局域网文件传输的实例
java实现局域网文件传输的实例
本文主要实现局域网文件传输的实例,对java的TCP知识,文件读写,Socket等知识的理解应用,很好的实例,大家参考下,
实现代码:
ClientFile.java
/** *更多资料欢迎浏览凯哥学堂官网:http://kaige123.com *@author小沫 */ packagecom.tcp.file; importjava.io.File; importjava.io.FileInputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.net.Socket; importjava.net.UnknownHostException; importjavax.swing.JProgressBar; publicclassClientFileextendsThread{ privatestaticStringip; privatestaticintport; privateStringfilepath; privatelongsize; privateJProgressBarjprogressbar; publicClientFile(Stringip,intport,Stringfilepath,JProgressBarjprogressbar){ this.ip=ip; this.port=port; this.filepath=filepath; this.jprogressbar=jprogressbar; } publicvoidrun(){ try{ Socketsocket=newSocket(ip,port); InputStreaminput=socket.getInputStream(); OutputStreamoutput=socket.getOutputStream(); Filefile=newFile(filepath); //第一次传输文件名字and文件的大小 Stringstr1=file.getName()+"\t"+file.length(); output.write(str1.getBytes()); output.flush(); byte[]b=newbyte[100]; intlen=input.read(b); Strings=newString(b,0,len); //如果服务器传输过来的是ok那么就开始传输字节 if(s.equalsIgnoreCase("ok")){ longsize=0; jprogressbar.setMaximum((int)(file.length()/10000));//设置进度条最大值 FileInputStreamfin=newFileInputStream(file); byte[]b1=newbyte[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(InterruptedExceptione){ e.printStackTrace(); } } output.close(); fin.close(); socket.close(); }else{ //传输的不是ok那么就弹出个信息框对方拒绝 javax.swing.JOptionPane.showMessageDialog(null,"对方拒绝接收此数据!"); } }catch(IOExceptione){ javax.swing.JOptionPane.showMessageDialog(null,"IOException"); } } }
ServerFile.java
/** *更多资料欢迎浏览凯哥学堂官网:http://kaige123.com *@author小沫 */ packagecom.tcp.file; importjava.io.*; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.net.InetAddress; importjava.net.ServerSocket; importjava.net.Socket; importjavax.swing.JFileChooser; importjavax.swing.JOptionPane; importjavax.swing.JProgressBar; publicclassServerFileextendsThread{ privateSocketsocket; privateJProgressBarjprogressbars; publicServerFile(Socketsocket,JProgressBarjprogressbars){ this.socket=socket; this.jprogressbars=jprogressbars; } publicvoidrun(){ try{ InputStreaminput=socket.getInputStream(); OutputStreamoutput=socket.getOutputStream(); byte[]b=newbyte[100]; intlen=input.read(b); Stringss=newString(b,0,len); String[]str1=ss.split("\t");//把接收到的信息按制表符拆分 Stringfilename=str1[0];//起始位文件名称 Stringfilesize=str1[1];//下标1位文件的大小 longsize=Long.parseLong(filesize); InetAddressip=socket.getInetAddress();//得到发送端的IP intport=socket.getPort();//得到发送端的端口 longs=size/1024/1024; Stringname="M"; if(s<1){ s=(size/1024); name="K"; }elseif(s>1024){ floats1=size/1024/1024; s=(size/1024/1024/1024); name="G多"; } //弹出确认款,显示对方的ip端口以及文件的名称和大小是否需要接收 inti=JOptionPane.showConfirmDialog(null, "来自:"+ip+":"+port+"\n文件名称:"+filename+"\n文件大小:"+s+name); //如果点击确认 if(i==JOptionPane.OK_OPTION){ //那么传输ok给发送端示意可以接收 output.write("ok".getBytes()); output.flush(); JFileChooserjf=newJFileChooser(); //存储到本地路径的夹子 jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jf.showOpenDialog(null); jprogressbars.setMaximum((int)(size/10000)); FileOutputStreamfout=newFileOutputStream(newFile(jf.getSelectedFile(),filename)); b=newbyte[1024*1024*2]; longsize1=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(IOExceptione){ javax.swing.JOptionPane.showMessageDialog(null,"IOException"); } } privatestaticServerSocketserver=null; //启动服务器 publicstaticvoidopenServer(intport,JProgressBarjprogressbar)throwsException{ newThread(){ publicvoidrun(){ try{ if(server!=null&&!server.isClosed()){ server.close(); } server=newServerSocket(port); newServerFile(server.accept(),jprogressbar).start(); }catch(IOExceptione){ javax.swing.JOptionPane.showMessageDialog(null,"IOException"); } } }.start(); } //关闭服务器 publicstaticvoidcloseServer(){ try{ server.close(); }catch(IOExceptione){ javax.swing.JOptionPane.showMessageDialog(null,"IOException"); } } }
SocketFileJFrame.java
/** *更多资料欢迎浏览凯哥学堂官网:http://kaige123.com *@author小沫 */ packagecom.tcp.file; importjava.awt.BorderLayout; importjava.awt.Dimension; importjava.awt.EventQueue; importjava.awt.Image; importjava.awt.Toolkit; importjavax.swing.JFrame; importjavax.swing.JPanel; importjavax.swing.border.EmptyBorder; importjava.awt.Color; importjavax.swing.JTabbedPane; importjava.awt.Panel; importjavax.swing.border.TitledBorder; importjavax.swing.UIManager; importjavax.swing.border.CompoundBorder; importjavax.swing.JLabel; importjava.awt.Font; importjavax.swing.JTextField; importjavax.swing.JToggleButton; importjavax.swing.JProgressBar; importjavax.swing.JButton; importjavax.swing.JFileChooser; importjavax.swing.event.AncestorListener; importjavax.swing.event.AncestorEvent; importjava.awt.event.ActionListener; importjava.io.IOException; importjava.awt.event.ActionEvent; publicclassSocketFileJFrameextendsJFrame{ privateJPanelcontentPane; privateJTextFieldtextField; privateJTextFieldtextField_1; privateJTextFieldtextField_2; privateJTextFieldtextField_3; privateJProgressBarprogressBar_2; /** *Launchtheapplication. */ publicstaticvoidmain(String[]args){ EventQueue.invokeLater(newRunnable(){ publicvoidrun(){ try{ SocketFileJFrameframe=newSocketFileJFrame(); frame.setVisible(true); }catch(Exceptione){ e.printStackTrace(); } } }); } /** *Createtheframe. */ publicSocketFileJFrame(){ 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); intwidth=Toolkit.getDefaultToolkit().getScreenSize().width;//获取分辨率宽 intheiht=Toolkit.getDefaultToolkit().getScreenSize().height;//获取分辨率高 //分辨率宽高减去软件的宽高除以2把软件居中显示 setBounds((width-747)/2,(heiht-448)/2,738,472); contentPane=newJPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(newEmptyBorder(5,5,5,5)); setContentPane(contentPane); contentPane.setLayout(null); JPanelpanel_1=newJPanel(); panel_1.setToolTipText(""); panel_1.setBorder(newTitledBorder(UIManager.getBorder("TitledBorder.border"), "\u6587\u4EF6\u63A5\u6536\u670D\u52A1\u5668",TitledBorder.LEADING,TitledBorder.TOP,null, newColor(0,0,0))); panel_1.setBackground(Color.WHITE); panel_1.setBounds(39,28,652,119); contentPane.add(panel_1); panel_1.setLayout(null); JLabellabel=newJLabel("\u7AEF\u53E3:"); label.setFont(newFont("新宋体",Font.PLAIN,22)); label.setBounds(26,31,66,35); panel_1.add(label); //端口文本框 textField=newJTextField(); textField.setFont(newFont("宋体",Font.PLAIN,19)); textField.setText("8080"); textField.setBounds(89,36,126,26); panel_1.add(textField); textField.setColumns(10); //服务器关闭启动的按钮 JToggleButtontglbtnNewToggleButton=newJToggleButton("\u542F\u52A8\u670D\u52A1\u5668"); tglbtnNewToggleButton.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ if(tglbtnNewToggleButton.isSelected()){ //如果是按下显示关闭服务器 tglbtnNewToggleButton.setText("关闭服务器"); textField.setEnabled(false);//按下之后端口文本框要设置不能写入 try{ //启动服务器 ServerFile.openServer(Integer.parseInt(textField.getText()) ,progressBar_2); }catch(Exceptione1){ javax.swing.JOptionPane.showMessageDialog(null,"Exception"); } }else{ //否启动服务器 tglbtnNewToggleButton.setText("启动服务器"); textField.setEnabled(true);////弹起之后端口文本框要设置可写状态 ServerFile.closeServer();//关闭服务器 } } }); tglbtnNewToggleButton.setFont(newFont("微软雅黑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=newJProgressBar(); progressBar_2.setBackground(Color.WHITE); progressBar_2.setForeground(newColor(255,218,185)); progressBar_2.setStringPainted(true); progressBar_2.setBounds(460,101,190,14); panel_1.add(progressBar_2); JPanelpanel_2=newJPanel(); panel_2.setToolTipText(""); panel_2.setBorder(newTitledBorder(UIManager.getBorder("TitledBorder.border"),"\u6587\u4EF6\u4F20\u8F93\u7AEF", TitledBorder.LEADING,TitledBorder.TOP,null,newColor(0,0,0))); panel_2.setBackground(Color.WHITE); panel_2.setBounds(39,191,652,202); contentPane.add(panel_2); panel_2.setLayout(null); //文件传输端的进度条 JProgressBarprogressBar_1=newJProgressBar(); progressBar_1.setFont(newFont("宋体",Font.PLAIN,18)); progressBar_1.setStringPainted(true); progressBar_1.setForeground(newColor(240,128,128)); progressBar_1.setBackground(Color.WHITE); progressBar_1.setBounds(96,169,472,20); panel_2.add(progressBar_1); JLabellblIp=newJLabel("IP\u5730\u5740:"); lblIp.setFont(newFont("微软雅黑Light",Font.PLAIN,20)); lblIp.setBounds(26,44,70,27); panel_2.add(lblIp); //IP地址文本框 textField_1=newJTextField(); textField_1.setText("127.0.0.1"); textField_1.setFont(newFont("新宋体",Font.PLAIN,20)); textField_1.setBounds(96,44,184,30); panel_2.add(textField_1); textField_1.setColumns(10); JLabellabel_1=newJLabel("\u7AEF\u53E3:"); label_1.setFont(newFont("微软雅黑Light",Font.PLAIN,20)); label_1.setBounds(308,42,80,30); panel_2.add(label_1); //端口文本框 textField_2=newJTextField(); textField_2.setText("8080"); textField_2.setFont(newFont("新宋体",Font.PLAIN,20)); textField_2.setColumns(10); textField_2.setBounds(359,44,80,30); panel_2.add(textField_2); //打开本地路径的按钮 JButtonbutton=newJButton("..."); button.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ JFileChooserjf=newJFileChooser(); 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); JLabellabel_2=newJLabel("\u8DEF\u5F84:"); label_2.setFont(newFont("微软雅黑Light",Font.PLAIN,15)); label_2.setBounds(489,50,44,18); panel_2.add(label_2); //显示文件路径框 textField_3=newJTextField(); textField_3.setEnabled(false); textField_3.setFont(newFont("微软雅黑Light",Font.PLAIN,20)); textField_3.setBounds(96,100,343,38); panel_2.add(textField_3); textField_3.setColumns(10); JLabellblNewLabel=newJLabel("\u6587\u4EF6:"); lblNewLabel.setFont(newFont("等线Light",Font.PLAIN,25)); lblNewLabel.setBounds(33,97,56,38); panel_2.add(lblNewLabel); //确定按钮 JButtonbutton_1=newJButton("\u786E\u5B9A"); button_1.addActionListener(newActionListener(){ publicvoidactionPerformed(ActionEvente){ ClientFileclient=newClientFile( textField_1.getText(),Integer.parseInt(textField_2.getText()), textField_3.getText(),progressBar_1); client.start(); } }); button_1.setForeground(newColor(255,255,0)); button_1.setBackground(newColor(233,150,122)); button_1.setFont(newFont("微软雅黑Light",Font.BOLD,20)); button_1.setBounds(475,100,91,38); panel_2.add(button_1); } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!