跨网络实现文件的传输-使用流和socket

跨网络实现文件的传输-使用流和socket

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo3 extends Thread{
    //接收线程
    InputStream is;
    @Override
    public void run() {
        synchronized (Demo3.class){
            byte[] arr = new byte[1024];
            int len = 0;
            try {
                int read = is.read(arr);
                //文件数据的输出
                FileOutputStream os = new FileOutputStream("/Users/lifuwei/Desktop/Test/test"+System.currentTimeMillis()+".txt");
                os.write(arr);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
import java.io.*;

public class Demo5 extends Thread{
    //发送线程
    OutputStream os;
    @Override
    public void run() {
        synchronized (Demo5.class){
            try {
                //读取本地文件
                FileInputStream msg = new FileInputStream("/Users/lifuwei/Desktop/Test/test.txt");
                byte[] arr = new byte[1024];
                int length = 0;
                while ((length=msg.read(arr))!= -1){
                    String str = new String(arr, 0, length);
                    os.write(arr,0,length);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

//客户端
public class Demo4 {
    public static void main(String[] args) throws Exception{
        Socket socket = new Socket("localhost",8888);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        Demo3 demo3 = new Demo3();
        Demo5 demo5 = new Demo5();
        demo3.is=is;
        demo5.os=os;
        demo3.start();
        demo5.start();

    }
}
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class Demo6 {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket server = serverSocket.accept();
        InputStream is = server.getInputStream();
        OutputStream os = server.getOutputStream();
        Demo3 demo3 = new Demo3();
        Demo5 demo5 = new Demo5();
        demo3.is =is;
        demo5.os = os;
        demo3.start();
        demo5.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值