廢話不多說了,直接給大家貼代碼了,具體代碼如下所示:
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
93
94
95
96
97
98
|
package com.lanqiao.demo2; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; /** * @author * @version 創建時間:2017年6月12日 上午8:47:37 * 類說明:服務端上傳一個txt類型的文件 * 注意:服務端是一直不關閉的 */ public class TestServer { // 這個路徑是我電腦上的一個記事本文件 public static void main(String[] args) { int count = 0 ; OutputStream os = null ; ServerSocket severscoket = null ; Socket s1 = null ; BufferedInputStream bis = null ; int len= 0 ; try { // 創建 Socket 服務 severscoket = new ServerSocket( 8888 ); while ( true ) { // 阻塞 s1 = severscoket.accept(); //服務端被連接的次數 count++; System.out.println( "---服務端開啟 " + count + " 次---" ); // 服務端寫入文件 os = s1.getOutputStream(); //創建一個BufferedInputStream對象讀取我電腦上的文件 bis = new BufferedInputStream( new FileInputStream(PATH)); //每次寫入512個字節 byte [] b = new byte [ 512 ]; while ((len = bis.read(b)) != - 1 ) { os.write(b, 0 , len); } s1.shutdownOutput(); os.flush(); } } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } finally { try { if (os != null ) os.close(); } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } } } package com.lanqiao.demo2; import java.io.BufferedInputStream; import java.io.IOException; import java.net.Socket; /** * @author * @version 創建時間:2017年6月12日 上午9:04:36 * 類說明:客戶端打印出從服務端下載的txt內容 */ public class TestClient { public static void main(String[] args) { BufferedInputStream bis = null ; Socket socket = null ; int len= 0 ; try { // 通過IP地址和端口號創建一個Socket對象 socket = new Socket( "127.0.0.1" , 8888 ); // 客戶端讀取文件 bis = new BufferedInputStream(socket.getInputStream()); // 每次讀512個字節 byte [] b = new byte [ 512 ]; //當讀取的字節不為空 循環打印下載的內容 while ((len = bis.read(b)) != - 1 ) { System.out.println( new String(b, 0 , len)); } } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } finally { //關閉客戶端的輸入流對象 和 Socket對象 try { if (bis!= null ) bis.close(); if (socket!= null ) socket.close(); } catch (IOException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } } } |
以上所述是小編給大家介紹的Java中Socket下載一個文本文件,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/lanqiao_zcg/article/details/73104855