当前位置:   article > 正文

Java BIO实现任意类型文件上传_java任意文件上传数据包

java任意文件上传数据包

Client端实现

package com.picture;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",5555);
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF(".png");
            FileInputStream fis = new FileInputStream("C:\\Users\\曹玉琦\\Desktop\\PIC\\NIO.png");
            byte[] Buffer = new byte[1024];
            int len;
            while ((len = fis.read(Buffer))>0)
            {
                dos.write(Buffer,0,len);
                dos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 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

这里我们使用DataOutputStream 来进行数据传输,我们先写入图片的格式“.png”再新FileInputStream,路径为我们要上传的目录。接着我们要新建一个字节数组,每次从输入流读取一个字节,然后写入输出流

Server端

package com.picture;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.UUID;

public class RunnableLoadPic implements Runnable{
    private Socket socket;

    public RunnableLoadPic(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String suffix = dis.readUTF();
            FileOutputStream fos = new FileOutputStream("C:\\Users\\曹玉琦\\Desktop\\新建文件夹 (2)\\" + UUID.randomUUID().toString() + suffix);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = dis.read(buffer))>0)
            {
                fos.write(buffer,0,len);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 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
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号