java-Socket文件上傳/進度條 – JAVA編程語言程序開發技術文章

客戶端代碼:
 
1、客戶端運行程序:
package wtb.khd;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
public class KHD{
 private boolean isnoClose = true;
 public boolean isIsnoClose() {
  return isnoClose;
 }
 public void setIsnoClose(boolean isnoClose) {
  this.isnoClose = isnoClose;
 }
 public static void main(String args[]){
  final KHD khd = new KHD();
  String filePath = "D:\\文件.zip";
  khd.setIsnoClose(true);
  File upload = new File(filePath);
  long fileLength = upload.length();
  String fileName = upload.getName();
  try {
   Socket client = null;
   client = new Socket("localhost",8888); //"localhost"—>服務器端IP
   OutputStream out = client.getOutputStream();
   DataOutputStream dos = new DataOutputStream(out);
   dos.writeUTF("文件名前綴_"+fileName);
   dos.writeLong(fileLength);
   FileInputStream fis = new FileInputStream(upload);
   byte[] buffer = new byte[2048];
   int len = 0;
   double scbl = 0; //文件上傳比例
   int scdx = 0;  //文件上傳大小
   final JinDuBar jdb = new JinDuBar("文件上傳",System.getProperty("user.dir")+"\\bin\\image\\jindutiao.gif");
   String[] uploadInfo = new String[]{"正在上傳文件:" + filePath, "文件名稱:"+ fileName,
     "上傳文件大小:"+fileLength+"字節", "已上傳:0字節", "上傳比例:0%"};
   JLabel[] labels = jdb.getLabels();
   for(int lxb = 0; lxb<labels.length; lxb++){
    labels[lxb].setText(uploadInfo[lxb]);
   }
   JProgressBar p = jdb.getProgress();
   JButton closeBtn = jdb.getCloseBtn();
  
   closeBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
     jdb.dispose();
     khd.setIsnoClose(false);
    }
   });
   while ((len = fis.read(buffer)) > 0 && khd.isnoClose) {
    Thread.sleep(100);
    scdx += len;
    scbl = (double)scdx/fileLength;
    int bl = (int)(scbl*100);
    dos.write(buffer, 0, len);
    p.setValue(bl);
    p.setString(bl+"%");
    String[] gxsc = new String[]{"已上傳:"+scdx+"字節", "上傳比例:"+bl+"%"};
    for(int lxb = 0; lxb<gxsc.length; lxb++){
     labels[lxb+3].setText(gxsc[lxb]);
    }
   }
   jdb.dispose();
   out.close();
   fis.close();
   client.close();
  } catch (Exception e1) {
   e1.printStackTrace();
  }
 }
}
 
/****************************/
2、進度條
package wtb.util;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JWindow;
@SuppressWarnings("serial")
public class JinDuBar extends JWindow{
 private JProgressBar progress;
 private JButton btn;
 private JLabel[] labels = new JLabel[5];
 private JButton closeBtn;
 public JProgressBar getProgress() {
  return progress;
 }
 public void setProgress(JProgressBar progress) {
  this.progress = progress;
 }
 public JButton getBtn() {
  return btn;
 }
 public void setBtn(JButton btn) {
  this.btn = btn;
 }
 public JLabel[] getLabels() {
  return labels;
 }
 public void setLabels(JLabel[] labels) {
  this.labels = labels;
 }
 public JButton getCloseBtn() {
  return closeBtn;
 }
 public void setCloseBtn(JButton closeBtn) {
  this.closeBtn = closeBtn;
 }
 public JinDuBar(String title,String bgImg){
  setAlwaysOnTop(true);
  setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  JPanel splash = new JPanel(new BorderLayout());
  JPanel top = new JPanel();
  top.setBackground(new Color(255,153,204));
  BorderLayout toplay = new BorderLayout();
  top.setLayout(toplay);
  JLabel tt = new JLabel(title);
  ImageIcon cloImg = new ImageIcon(System.getProperty("user.dir") + "/bin/image/4.png");
  closeBtn = new JButton("close ",cloImg);
  closeBtn.setBackground(new Color(255,153,204));
  top.add(tt, BorderLayout.CENTER);
  top.add(closeBtn, BorderLayout.EAST);
  top.add(new JLabel("   "), BorderLayout.WEST);
  splash.add(top,BorderLayout.NORTH);
  ImageIcon img = new ImageIcon(bgImg);
  btn = new JButton(img);
  getLayeredPane().add(btn, new Integer(Integer.MIN_VALUE));
        btn.setBounds(0,0,img.getIconWidth(),img.getIconHeight());
        GridLayout gl = new GridLayout(this.getLabels().length,1); //labels.length行1列
        btn.setLayout(gl);
        for(int i = 0; i<labels.length; i++){
         this.getLabels()[i] = new JLabel("000"+i);
         btn.add(labels[i]);
        }
  splash.add(btn, BorderLayout.CENTER);
  progress = new JProgressBar(1, 100);
  progress.setStringPainted(true);
  progress.setBorderPainted(false);
  progress.setString("0%");
  progress.setBackground(Color.WHITE);
  splash.add(progress, BorderLayout.SOUTH);
  setContentPane(splash);
  Dimension screen = getToolkit().getScreenSize();
  setSize(img.getIconWidth(), img.getIconHeight()+60);
  setLocation((screen.width – getSize().width)/2, (screen.height – getSize().height)/2);
  new DragJWindow(this, splash);  //設置窗口可拖動www.aiwalls.com
  setVisible(true);
 }
}
/********************************/
3、設置Window窗口可拖動
package wtb.util;
import javax.swing.SwingUtilities;
import java.awt.Component;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
public class DragJWindow {
    private Window fWindow;
    private Component fComponent;
    private int dX;
    private int dY;
    public DragJWindow(Window window, Component component) {
        fWindow = window;
        fComponent = component;
        fComponent.addMouseListener(createMouseListener());
        fComponent.addMouseMotionListener(createMouseMotionListener());
    }
    private MouseListener createMouseListener() {
        return new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                Point clickPoint = new Point(e.getPoint());
                SwingUtilities.convertPointToScreen(clickPoint, fComponent);
                dX = clickPoint.x – fWindow.getX();
                dY = clickPoint.y – fWindow.getY();
            }
        };
    }
    private MouseMotionAdapter createMouseMotionListener() {
        return new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                Point dragPoint = new Point(e.getPoint());
                SwingUtilities.convertPointToScreen(dragPoint, fComponent);
                fWindow.setLocation(dragPoint.x – dX, dragPoint.y – dY);
            }
        };
    }
}
/******************************************/
/******************************************/
服務器端:
1、服務器端運行程序
package wtb.fwq;
import java.net.ServerSocket;
import java.net.Socket;
import wtb.fwq.UploadThread;
public class UploadServer {
 public final static String fileDir = "E:\\wtb";
 public static void main(String args[]) throws Exception {
  ServerSocket server = null ;
  Socket client = null ;
  server = new ServerSocket(8888);
  while(true){
   client = server.accept();
   //為每個用戶設置一個線程
   UploadThread uft = new UploadThread(client, fileDir);
   new Thread(uft).start();
  }
 }
}
 
/*************************************/
2、為每個用戶設置一個線程的線程類
package wtb.fwq;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class UploadThread implements Runnable {
 private Socket client;
 private String fileDir;
 private String fileName;
 public UploadThread(Socket client, String fileDir){
  this.client = client;
  this.fileDir = fileDir;
 }
 public void run(){
  InputStream in = null ;
  FileOutputStream fos = null;
  try {
   in = client.getInputStream();
   DataInputStream dis = new DataInputStream(in);
   fileName = dis.readUTF();
   long fileLength = dis.readLong();
   long xzdx = 0;
   fos = new FileOutputStream(fileDir+File.separator+fileName);
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = dis.read(buffer)) > 0)
   {
    fos.write(buffer, 0, len);
    xzdx += len;
   }
   fos.flush();
   fos.close();
   in.close();
   client.close() ;
   if(xzdx != fileLength){  //如果文件未傳完,則刪除傳到服務器端的文件
    File f = new File(fileDir+File.separator+fileName);
    f.delete();
   }
  }catch(Exception e){
   System.out.println("異常!!!!");
  }
 }
}
/************************/
運行結果視圖: 

 

摘自  天天笑一下

發佈留言