使用TCP完成文本文件上傳,要求客戶端讀取文本文件使用字符流,
服務端把文本保存也需要使用字符流寫出去
TCP服務端
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class TCPServer4 {
- public static void main(String[] args) throws IOException {
- //創建服務端對象
- ServerSocket ss = new ServerSocket(8090) ;
- //獲取客戶端對象
- Socket s = ss.accept() ;
- //獲取字節輸入流對象
- InputStream in = s.getInputStream() ;
- //創建字符輸入流緩沖區
- BufferedReader br = new BufferedReader(new InputStreamReader(in)) ;
- //創建字符輸出流緩沖區
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(“E:/tcp.txt”)));
- String line = null ;
- while((line = br.readLine())!=null) {
- bw.write(line);
- //換行
- bw.newLine();
- //刷新緩沖區,將數據寫到文件中
- bw.flush();
- }
-
- //存儲文件完成,向客戶端發送消息
- OutputStream os = s.getOutputStream() ;
- os.write(“上傳完成……”.getBytes());
- //關閉流
- bw.close();
- os.close();
- }
- }
客戶端:
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- public class TCPClient4 {
- public static void main(String[] args) throws IOException {
- //創建客戶端對象
- Socket s = new Socket(“127.0.0.1″,8090);
- //創建字節輸出流對象
- OutputStream os = s.getOutputStream() ;
- //定義輸出轉換,把字符輸出流轉換成字節輸出流
- OutputStreamWriter osw = new OutputStreamWriter(os) ;
- //為高效寫出數據,定義字符輸出緩沖區對象
- BufferedWriter bw = new BufferedWriter(osw) ;
- //創建字符輸入緩沖區對象
- BufferedReader br = new BufferedReader(new FileReader(“1.txt”));
- String line = null ;
- while((line = br.readLine())!=null){
- bw.write(line);
- bw.newLine();
- bw.flush();
- }
- //關閉輸出流,給服務端發送數據發送結束的標記
- s.shutdownOutput();
- //======文件上傳完畢=========
- //接收服務器返回的消息
- InputStream in = s.getInputStream() ;
- byte[] buf = new byte[1024] ;
- int len = in.read(buf);
- System.out.println(new String(buf,0,len));
- br.close();
- s.close();
- }
- }