Java教程

java服务器上传文件案例

本文主要是介绍java服务器上传文件案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

客户端

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

public class Client {
    public static void main(String[] args) throws IOException {
        //创建对象
        Socket socket = new Socket(InetAddress.getLocalHost(), 12345);
        //读取文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader("E:\\Workpace\\ReviceSocket1.java"));
        //封装输出流
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null){
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        socket.shutdownOutput();
        bufferedReader.close();
        //接受服务器反馈
        BufferedReader bufferedReader1 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        System.out.println(bufferedReader1.readLine());

        socket.close();
    }
}


服务端

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

public class Server {
    public static void main(String[] args) throws IOException {
        //创建对象
        ServerSocket serverSocket = new ServerSocket(12345);
        Socket accept = serverSocket.accept();
        int count = 0;
        String filename = "Example1\\ReviceSocket"+count+".java";
        File file = new File(filename);
        if (!file.exists()){
            count++;
            filename = "Example1\\ReviceSocket"+count+".java";
        }
        //下载文件
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename));
        //封装输入流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null){
            bufferedWriter.write(line);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        //输出反馈信息
        BufferedWriter bufferedWriter1 = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
        bufferedWriter1.write("文件已上传");
        bufferedWriter1.newLine();
        bufferedWriter1.flush();
        bufferedWriter.close();
        serverSocket.close();
    }
}


这篇关于java服务器上传文件案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!