客户端服务端网络编程---实现上传文件

客户端:

ublic class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		File file = getFile();

		Socket socket = new Socket("127.0.0.1", 8888);
		BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		PrintStream output = new PrintStream(socket.getOutputStream());
		output.println(file.getName());
		String result = input.readLine();
		if ("文件已存在".equals(result)) {
			System.out.println("你上传的文件已存在,请重新输入:");
			socket.close();
		}

		FileInputStream fileinput = new FileInputStream(file);
		byte[] arr = new byte[8192];
		int i;
		while ((i = fileinput.read(arr)) != -1) {
			output.write(arr, 0, i);
		}
		
		fileinput.close();
		socket.close();

	}

	private static File getFile() {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入文件路径:");

		String line = sc.nextLine();
		while (true) {//判断文件是否合法
			File file = new File(line);
			if (file.isDirectory()) {
				System.out.println("输入的是文件夹路径,请重新输入:");
			} else if (!file.exists()) {
				System.out.println("输入路径不存在,请重新输入:");
			} else {
				return file;
			}
		}
	}
}

服务端:


public class Server {
	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(8888);
		System.out.println("Server is running");
		while(true) {
			Socket socket = server.accept();
			new Thread() {
				public void run() {
					try {
						InputStream inputStream = socket.getInputStream();
						BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));
						PrintStream output = new PrintStream(socket.getOutputStream());
						String fileName = input.readLine();//接受客户端的文件名
						
						File dir = new File("upload");
						dir.mkdir();
						File file = new File(dir,fileName);//封装成file对象,父级目录upload
						
						if(file.exists()) {
							output.println("文件已存在");
							socket.close();
						}
						
						FileOutputStream fileoutput = new FileOutputStream(file);
						byte[] arr = new byte[8192];
						int i;
						
						while((i = inputStream.read(arr)) != -1){
							fileoutput.write(arr,0,i);
						}
						fileoutput.close();
						socket.close();
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}.start();
			
		}
	}
}

 输入一个文件的路径:

客户端服务端网络编程---实现上传文件_第1张图片

运行结果:

在项目的目录下成功创建upload文件夹,并将文件上传到文件夹中

客户端服务端网络编程---实现上传文件_第2张图片

你可能感兴趣的:(客户端服务端网络编程---实现上传文件)