自己写文件传输类



package ftpsample;
import java.io.*;
import java.net.*;
public class ClientFTPSample{
 private Socket s=null;
 public ClientFTPSample(){
  createConnection();
 }
 public void createConnection(){
  try{
   s=new Socket("127.0.0.1",9090);
   
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 private void getFile(){
  String savepath="d://";
  int buffersize=8192;
  byte buf[]=new byte[buffersize];
  long length=0;
  try{
   DataInputStream dis=new DataInputStream(new BufferedInputStream(s.getInputStream()));
   savepath+=dis.readUTF();
   DataOutputStream dos=new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(savepath))));
   length=dis.readLong();
   System.out.println("file length"+length);
   int read=0;
   while((read=dis.read(buf))!=-1){
    dos.write(buf,0,read);
    System.out.println("file accpete "+savepath);
   }
   dos.close();
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 public static void main(String args[]){
  new ClientFTPSample().getFile();
 }
}


package ftpsample;
import  java.net.*;
import java.io.*;
public class FTPSocket{
 String filepath="e://msdia80.dll";
 int port=9090;
 void start(){
  Socket s=null;
  try{
   ServerSocket ss=new ServerSocket(port);
   while(true){
    File file=new File(filepath);
    System.out.println("file length:"+file.length());
    s=ss.accept();
    DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
    DataOutputStream dos=new DataOutputStream(s.getOutputStream());
    dos.writeUTF(file.getName());
    dos.writeLong((long)file.length());
    int  buffersize=8192;
    byte buf[]=new byte[buffersize];
    while(true){
     int read=0;
     if(dis!=null){
      read=dis.read(buf);
     }
     if(read==-1){
      break;
     }
     dos.write(buf,0,read);
    }
    dis.close();
    s.close();
    System.out.println("filesend  over");
   }
  }catch(Exception e){e.printStackTrace();}
 }
 public static void main(String args[]){
  new FTPSocket().start();
 }
 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值