日期:2014-05-20  浏览次数:21033 次

关于文件传输的问题~
 
  刚学java不久,对于类的理解不够深入,同学发我个文件传输的程序要偶讲讲其中类的功能介绍,以及类中主要方法,请各位大侠帮帮忙~

(服务器端)Receive.java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class Receive implements 

ActionListener {
  JFileChooser jc;
  JFrame f;
  ServerSocket ss;
  Socket socket;
  JButton b1,b2;
  TextArea txt;
  DataInputStream din;
  DataOutputStream dout;

public Receive() {
  //界面布局
  jc = new JFileChooser();
  f = new JFrame("文件接收");
  f.setLocation(100,300);
  f.setDefaultCloseOperation

(JFrame.EXIT_ON_CLOSE); 
  b1 = new JButton("另存

为",new ImageIcon("1.gif"));
  b2 = new JButton("取消",new 

ImageIcon("2.gif"));
  txt=new TextArea(10,40);
  JScrollPane scrollpane = new 

JScrollPane(txt);
  JPanel p = new JPanel();
  p.add(b1);
  p.add(b2);
  Container c = 

f.getContentPane();
  c.setLayout(new 

BorderLayout());
  c.add

(txt,BorderLayout.CENTER);
  c.add(p,BorderLayout.NORTH);
  f.setSize(400,150);
  f.setVisible(true);
  //注册事件
  b1.addActionListener(this);
  b2.addActionListener(this);
   
 try { ss = new ServerSocket(4321);
  while(!ss.isClosed()){
  socket = ss.accept();
  din = new DataInputStream

(socket.getInputStream());
  txt.append("开始接受文

件:"+din.readUTF()+"\n");
  }
  } catch (IOException e) {
  if(ss.isClosed()){
  txt.append("End");
  }else{
  e.printStackTrace();
   

}
  }
}

public void actionPerformed

(ActionEvent e)
  {
  //如果同意接收同,则启动

线程接收文件
  if(e.getSource()==b1)
  { jc.showSaveDialog(f);
  FileReceive r= new 

FileReceive(jc.getSelectedFile

(),socket);
  r.start();
  }else if(e.getSource()==b2){ 
  System.out.println("用

户取消接收!"+"\n");
  System.exit(0);
  }
  }


class FileReceive extends Thread
{ File rfile;
  Socket socket;
 FileReceive(File rfile, Socket 

socket) {
  this.rfile = rfile;
  this.socket = socket;
   

  }
   

public void run() {

 //判断用户是否保存文件
 if(rfile == null){ txt.append("没

有保存!"+"\n"); return;
  }
 else{
  //保存文件后,则向发送方

发送同意(true)
  try {
  dout = new 

DataOutputStream

(socket.getOutputStream());
  dout.writeBoolean(true);
  } catch (IOException e) {
  e.printStackTrace();
  }
  }txt.append("开始接

收..."+"\n");