package com.main; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.Socket; /** * Îļþ´«ÊäClient¶Ë
* ¹¦ÄÜ˵Ã÷£º * * @author ³ÐÇΰ * @Date 2019Äê02ÔÂ14ÈÕ * @version 1.0 */ public class FileTransferClient extends Socket { private static final String SERVER_IP = "127.0.0.1"; // ·þÎñ¶ËIP private static final int SERVER_PORT = 8899; // ·þÎñ¶Ë¶Ë¿Ú private Socket client; private FileInputStream fis; private DataOutputStream dos; /** * ¹¹Ô캯Êý
* Óë·þÎñÆ÷½¨Á¢Á¬½Ó * @throws Exception */ public FileTransferClient() throws Exception { super(SERVER_IP, SERVER_PORT); this.client = this; System.out.println("Cliect[port:" + client.getLocalPort() + "] ³É¹¦Á¬½Ó·þÎñ¶Ë"); } /** * Ïò·þÎñ¶Ë´«ÊäÎļþ * @throws Exception */ public void sendFile() throws Exception { try { File file = new File("D:\\tb_battinf.sql"); if(file.exists()) { fis = new FileInputStream(file); dos = new DataOutputStream(client.getOutputStream()); // ÎļþÃûºÍ³¤¶È dos.writeUTF(file.getName()); dos.flush(); dos.writeLong(file.length()); dos.flush(); // ¿ªÊ¼´«ÊäÎļþ System.out.println("======== ¿ªÊ¼´«ÊäÎļþ ========"); byte[] bytes = new byte[1024]; int length = 0; long progress = 0; while((length = fis.read(bytes, 0, bytes.length)) != -1) { dos.write(bytes, 0, length); dos.flush(); progress += length; System.out.print("| " + (100*progress/file.length()) + "% |"); } System.out.println(); System.out.println("======== Îļþ´«Êä³É¹¦ ========"); } } catch (Exception e) { e.printStackTrace(); } finally { if(fis != null) fis.close(); if(dos != null) dos.close(); client.close(); } } /** * Èë¿Ú * @param args */ public static void main(String[] args) { try { FileTransferClient client = new FileTransferClient(); // Æô¶¯¿Í»§¶ËÁ¬½Ó client.sendFile(); // ´«ÊäÎļþ } catch (Exception e) { e.printStackTrace(); } } }