码迷,mamicode.com
首页 > 编程语言 > 详细

java下socket传文件

时间:2015-09-08 21:47:36      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

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();

    }

}

 

java下socket传文件

标签:

原文地址:http://www.cnblogs.com/zywf/p/4792849.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!