java下socket传文件

package cn.stat.p4.ipdemo;

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 server { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(10000); Socket s=ss.accept(); BufferedReader bufr=new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedWriter bufw=new BufferedWriter(new FileWriter("2.txt")); String line=null; while((line=bufr.readLine())!=null)
{
bufw.write(line);
bufw.newLine();
bufw.flush();
} PrintWriter pw=new PrintWriter(s.getOutputStream(),true); pw.println("完成"); pw.close();
bufw.close();
bufr.close();
s.close();
ss.close(); } }
package cn.stat.p4.ipdemo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException; public class clent { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
//创建socket
Socket s=new Socket("192.168.1.103",10000); //创建读取对象
BufferedReader bufr=new BufferedReader(new FileReader("1.txt")); //创建写入对象
PrintWriter pw=new PrintWriter(s.getOutputStream(), true); String line=null; while((line=bufr.readLine())!=null)
{
pw.println(line);
}
//告诉服务端,发送完成
s.shutdownOutput(); //接收返回数据
BufferedReader bfr=new BufferedReader(new InputStreamReader(s.getInputStream()));
String text=bfr.readLine();
System.out.println(text); bfr.close();
bufr.close();
s.close(); } }
上一篇:201521123045 《JAVA程序设计》 第14周学习总结


下一篇:Java语言程序设计(基础篇)第二章