whyclj
2019-02-18 9ab87ec428de8a4b9c3ee8dcaa79110b32c59ca2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.main;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
 
/**
 * Îļþ´«ÊäClient¶Ë<br>
 * ¹¦ÄÜ˵Ã÷£º
 *
 * @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;
 
    /**
     * ¹¹Ô캯Êý<br/>
     * Óë·þÎñÆ÷½¨Á¢Á¬½Ó
     * @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();
        }
    }
 
}