java文件上传功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java文件上传功能

꧁এ悲宸๓₯㎕   2022-05-23 我要评论

文件上传的步骤:

服务器端步骤:

1、创建ServerSocket

2、调用accept获得客户端Socket

3、定义字节数组

4、创建文件输出流,获得客户端输入流

5、循环读取输入流的字节,写入到文件输出流

客户端步骤:

1、创建Socket

2、获得socket对象输出流

3、创建文件输入流

4、循环读取文件输入流字节,写入到输出流

代码实现:

服务器端:

public class FileServer {
    public static final int PORT = 8888;
    public static final String PATH = "D:\\upload\\";

    public void start(){
        System.out.println("start...");
        try (   //创建服务器端对象
                ServerSocket server = new ServerSocket(PORT);){
            while (true){
                Socket socket = server.accept();
                try (   //创建文件输出流和网络输入流
                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        //读取哭护短发来的文件名,创建文件输出流
                        FileOutputStream out = new FileOutputStream(PATH+in.readUTF())){
                        int len = 0;
                        byte[] buffer = new byte[1024];
                        while ((len = in.read(buffer)) != -1){
                            out.write(buffer,0,len);
                        }
                    System.out.println("服务器保存完毕!");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileServer().start();
    }

}

客户端:

public class FileClient {
    /**
     * 发送文件
     */
    public void sendFile(String ip,int port,String path){
        File file = new File(path);
        try (
            //创建连接,创建文件输入流,网络输出流
            Socket socket = new Socket(ip,port);
            InputStream in = new FileInputStream(path);
            DataOutputStream out = new DataOutputStream(socket.getOutputStream())){
            //先发送文件给服务器
            out.writeUTF(file.getName());
            out.flush();
            //读取本地文件,写入到网络输出流中
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len  = in.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            System.out.println("客户端发送完毕!");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileClient().sendFile("192.168.31.226",8888,"C:\\Users\\admin\\Desktop\\C.txt");
    }
}

实现效果:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们