文件上传(客户端---服务端)

package upload;

import util.StreamUtil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Copyright (C), 2018-2021, Mr.Lin
 * Author: Mr.Lin
 * Date: 2021/12/1 23:23
 * FileName: TCPFileUploadCliet
 * Description: 文件上传的客户端
 */
public class TCPFileUploadCliet {
    public static void main(String[] args) throws IOException {

        //连接服务端端口
        Socket socket = new Socket(InetAddress.getLocalHost(),7777);
        String fildPath="E:\\Mu\\1.png";
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fildPath));

        byte[] bytes = StreamUtil.streamToByteArray(bis);
//通过socket获取到输出流,将bytes数据发送到服务端
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        //将字节流数组内容写入到数据通道
        bos.write(bytes);
        bis.close();
        socket.shutdownOutput();//设置写入数据的结束标记

        bos.close();
        socket.close();



    }
}
package upload;

import com.sun.org.apache.bcel.internal.generic.NEW;
import util.StreamUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Copyright (C), 2018-2021, Mr.Lin
 * Author: Mr.Lin
 * Date: 2021/12/1 23:24
 * FileName: TCPFileUploadServer
 * Description: 文件上传服务端
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws IOException {
        //创建监听端口
        ServerSocket serverSocket = new ServerSocket(7777);
        //等待连接
        Socket socet = serverSocket.accept();

        BufferedInputStream bis = new BufferedInputStream(socet.getInputStream());

        byte[] b = StreamUtil.streamToByteArray(bis);
        String filPath="E:\\Mu1\\1.png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filPath));
        bos.write(b);
        bos.close();


        bis.close();
        socet.close();
        serverSocket.close();


    }
}

自制工具类

package util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Copyright (C), 2018-2021, Mr.Lin
 * Author: Mr.Lin
 * Date: 2021/12/1 23:35
 * FileName: StreamUtil
 * Description:字节转换工具
 */
public class StreamUtil {
    /**
     * 功能:将输入流转换成byte[],即可以把文件类容读入到byte[]
     * @param is
     * @return
     * @throws IOException
     */
    public static byte[] streamToByteArray(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();//创建访问数组输出流对象
        byte[] b = new byte[1024];//字节数组
        int len;
        while ((len=is.read(b))!=-1){//循环读取
            bos.write(b,0,len);//把读取的数据写入到数组流中
        }
        byte[] array=bos.toByteArray();
        bos.close();
        return array;

    }
}

 

上一篇:FastAPI之挂载应用程序


下一篇:基于FPGA的4位减法器结构化设计