Java上传文本文件

练习:上传文件

客户端:UploadClent.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class UploadClent {
   public static void main(String[] args) throws IOException {
      System.out.println("客户端启动......");
      Socket socket = new Socket(InetAddress.getLocalHost(), 45670);
      BufferedReader bufr = new BufferedReader(new FileReader("C:\\demo.txt"));
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      String line = null;
      while ((line = bufr.readLine()) != null) {
        out.println(line);
      }
      // out.println("over");//很烂的方法,有限制
      // out.println("!@#$%^");
      socket.shutdownOutput();
      BufferedReader bufIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      String str = bufIn.readLine();
      System.out.println(str);
      bufr.close();
      socket.close();
   }
}


服务端:UploadServer.java

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class UploadServer {
   public static void main(String[] args) throws IOException {
      System.out.println("服务端启动.........");
      ServerSocket ss = new ServerSocket(45670);
      Socket socket = ss.accept();
      System.out.println(socket.getInetAddress().getHostAddress()+ " is connected...");
      BufferedReader bufr = new BufferedReader(new InputStreamReader( socket.getInputStream()));
      BufferedWriter bufw = new BufferedWriter(new FileWriter("C:\\server.txt"));
      String line = null;
      while ((line = bufr.readLine()) != null) {
        // if("over".equals(line))
        // break;
        bufw.write(line);
        bufw.newLine();
        bufw.flush();
      }
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      out.println("上传成功");
      socket.close();
      ss.close();
      bufw.close();
   }
}