java上传文件例子

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.keqi.client.core.ui;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * 上传文件demo
 *
 * @author jwang
 * @date 2013.3.15
 */
public class LicenseDialog extends javax.swing.JDialog {
   
    private JFileChooser chooser;
    private FileNameExtensionFilter filter;
    private Socket socket;
    private DataOutputStream doStream;
   
    /**
     * Creates new form LicenseDialog
     */
    public LicenseDialog() {
        super(KeqiApplication.getKeqiApplication().getApplicationFrame(),true);
        initComponents();
        setLocationRelativeTo(null);
    }
   
    /**
     * 获得license的路径
     *
     * @author jwang
     * @date 2013.3.14
     * @return
     */
    public String getLicensePath(){
        return jTextField1.getText().toString();
    }
   
    /**
     * 显示license位置
     *
     * @author jwang
     * @date 2013.3.14
     * @param path
     */
    public void setLicensePath(String path){
        jTextField1.setText(path);
    }
   
    private void initConnection(){
        try {
            socket = new Socket("10.20.65.156", 8888);
            doStream = new DataOutputStream(socket.getOutputStream());
        } catch (UnknownHostException ex) {
            Logger.getLogger(LicenseDialog.class.getName()).log(Level.SEVERE, "远程地址连接出错", ex);
        } catch (IOException ex) {
            Logger.getLogger(LicenseDialog.class.getName()).log(Level.SEVERE, "检查连接地址和端口", ex);
        }
       
    }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("宋体", 0, 18)); // NOI18N
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/keqi/client/login/Bundle"); // NOI18N
        jLabel1.setText(bundle.getString("license.tip.first")); // NOI18N

        jTextField1.setBackground(new java.awt.Color(255, 255, 255));
        jTextField1.setEditable(false);

        jButton1.setText(bundle.getString("license.selected.file")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText(bundle.getString("license.tip.second")); // NOI18N

        jButton2.setText(bundle.getString("license.tip.third")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 252, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextField1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton1))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(149, 149, 149)
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(142, 142, 142)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * 浏览文件按钮
     *
     * @author jwang
     * @date 2013.3.14
     * @param evt
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        chooser = new JFileChooser(); // 文件选择器
        // 过滤license文件类型
        filter = new FileNameExtensionFilter("*.lic", "lic");
        chooser.setFileFilter(filter);
        int result = chooser.showOpenDialog(this);
        if(result == JFileChooser.APPROVE_OPTION){
            setLicensePath(chooser.getSelectedFile().getAbsolutePath());
            initConnection();
        }
    }
   
    /**
     * 导入license文件按钮
     *
     * @author jwang
     * @date 2013.3.14
     * @param evt
     */
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
        String path = getLicensePath();
        if(path != null && !path.isEmpty()){
            File file = new File(path);
            if(file.isFile() && file.exists()){
                try {
                    System.out.println("导入 : " + file.getName());
                    // 把文件传到服务端
                    doStream.writeUTF(file.getName());
                    FileInputStream fiStream = new FileInputStream(file);
                    BufferedInputStream biStream = new BufferedInputStream(fiStream);
                    int n;
                    while((n = biStream.read()) != -1){
                        doStream.write(n);
                    }
                    biStream.close();
                    fiStream.close();
                    doStream.flush();
                    doStream.close();
                    initConnection();
                    this.dispose();
                } catch (IOException ex) {
                    Logger.getLogger(LicenseDialog.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                String msg = java.util.ResourceBundle.getBundle("com/keqi/client/core/ui/Bundle").getString("license.file.is.not.file.tip");
                JOptionPane.showMessageDialog(null, msg);
            }
        } else {
            String msg = java.util.ResourceBundle.getBundle("com/keqi/client/core/ui/Bundle").getString("license.file.isempty.tip");
            JOptionPane.showMessageDialog(this, msg);
        }
       
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       new LicenseDialog().setVisible(true);
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

************* 服务端*****************

 

*/
package com.keqi.server.license;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 服务器license验证
 *
 * @author jwang
 * @date 2013.3.14
 */
public class HostLicense {
   
    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(8888);
            System.out.println("Server start... Port : 8888");
            while(true){
                Socket client = server.accept();
                new ServerThread(client).start();
            }
        } catch (IOException ex) {
            Logger.getLogger(HostLicense.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
  
}

/**
 * 获得license文件线程
 *
 * @author jwang
 * @date 2013.3.14
 */
class ServerThread extends Thread{

    String fileName = null; // 上传license文件名
    DataInputStream diStream = null; // 数据输入流
    FileOutputStream foStream = null; // 文件输出流
    BufferedOutputStream boStream = null; // 输出流缓冲区
   
    public ServerThread(Socket client) throws IOException{
        diStream = new DataInputStream(client.getInputStream());
    }
   
    @Override
    public void run(){
        try {
            int count;
            while(true){
                if(fileName == null){
                    fileName = diStream.readUTF();
                    System.out.println("license file : " + System.getProperty("user.dir"));
                    foStream = new FileOutputStream(System.getProperty("user.dir") + File.separator + fileName);
                    boStream = new BufferedOutputStream(foStream);
                } else {
                    while((count = diStream.read()) != -1){
                        boStream.write(count);
                    }
                    boStream.flush();
                    boStream.close();
                    this.notify();
                    return;
                }
           
            }
           
        } catch (Exception e) {
        }
    }
}

 

 

 

 

 

 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值