public class UClient extends JFrame implements ActionListener{ private JButton open =new JButton( "选择文件"); private DatagramPacket dp ;// 数据报包 private DatagramSocket ds ;// 数据报 Socket private String filename ;// 保存选择的文件的名字 private FileInputStream fis ;// 输入流,用来读取磁盘文件 byte [] buf =new byte [10240]; // 字节数组,存放读取的文件的数据构造方法,构建界面 public UClient(){ this .setSize(150,100); this .setTitle( "发送文件"); this .setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); this .setLayout( new FlowLayout()); this .add( open ); open .addActionListener( this ); this .setVisible( true ); }public void start(){ try {ds =new DatagramSocket(1234); // 首先启动 Socket }catch (SocketException e) { (); }}public static void main(String[] args) { new UClient().start(); }// 事件响应代码 public void actionPerformed(ActionEvent e) { JFileChooser jfc =new JFileChooser(); // 文件选择器组件 ( this ); // 显示打开对话框 filename =().getPath(); //获得选中文件路径和名字 try {fis =new FileInputStream( filename ); int c; while ((c =fis .read( buf ))!=-1){ // 读文件,数据存入 buf 字节数组利用 buf 做数据报包dp =new DatagramPacket( buf ,c, new InetSocketAddress( "" ,4567)); ds .send( dp ); // 发送出去}fis .close(); }catch (IOException e2) { (); }}} private JButton save = new JButton(" 保存文件"); private DatagramPacket dp; private DatagramSocket ds; private FileOutputStream fos ; private FileInputStream fis; privat
java_cs文件传输(精) 来自淘豆网m.daumloan.com转载请标明出处.