简版的文件传输

利用TCP协议下一个简版的文件传输

发送文件客户端

1 package Package1;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.IOException;
 8 import java.net.InetAddress;
 9 import java.net.Socket;
10 import java.net.UnknownHostException;
11 
12 public class 发送文件客户端 {
13 
14     public static void main(String[] args) throws IOException, IOException {
15         try(
16                 Socket s=new Socket(InetAddress.getByName("localhost"),9002);
17                 BufferedInputStream  bis=new BufferedInputStream(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\4.19.txt")));
18                 BufferedOutputStream bos=new BufferedOutputStream(s.getOutputStream());
19                 
20                 ){
21                     byte[] bt=new byte[1024];
22                     int count=0;
23                     while((count=bis.read(bt))!=-1) {
24                         bos.write(bt,0,count);
25                     }
26                     bos.flush();
27         }catch(Exception e) {
28             e.printStackTrace();
29         }
30 
31     }
32 
33 }

服务器端:

 1 package Package1;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.net.ServerSocket;
 9 import java.net.Socket;
10 
11 public class 发送文件服务器端 {
12 
13     public static void main(String[] args) throws Exception {
14         try(
15                 ServerSocket ss=new ServerSocket(9002);
16                 
17                 ){
18                     try(
19                             Socket s=ss.accept();
20                         BufferedInputStream bis=new BufferedInputStream(s.getInputStream());                        
21                         BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File("upload\\2.txt")));
22                             
23                             ){
24                             byte[] bt=new byte[1024];
25                             int count=0;
26                             while((count=bis.read())!=-1) {
27                                 bos.write(bt,0,count);
28                             }
29                     }
30         }
31 
32     }
33 
34 }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值