A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 湛添友 中级黑马   /  2014-5-18 22:10  /  1294 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

写了个tcp 协议 客户端上服务端上传文件的代码  里面有一个地方不同 请指教

/*
while((len=bisPicture.read())!=-1){
   
    //我要问的问题就在这里
   
    System.out.print("");//这里我不知道是什么原因 把这行注释了 就不能上传成功了 服务端存储的文件是没有内容的文件
    bos.write(len);
   }


*/


package com.zty.net;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.Executors;

public class UploadPictureByTcp {
public static void main(String args[]){//主函数需要接受文件路径参数
  if(args==null){
   System.out.println("请输入要出入的文件路径");
  }
  //如果输入了带空格的路径名 就应该重新拼接
  String name=null;//完整的路径名
  String fileName = null;
  if(args.length>1){
   StringBuilder pathName=new StringBuilder();
   for(int x=0;x<args.length;x++){
    if(x==(args.length-1)){
     pathName.append(args[x]);
    }
    pathName.append(args[x]+" ");
   }
   name = pathName.toString();
   fileName=name.substring(name.lastIndexOf("\\")+1);
  }else{
   name=args[0];
   fileName=name.substring(name.lastIndexOf("\\")+1);
  }
  
  
  
  File filePath=new File(name);//把路径名封装成对象
  if(!filePath.exists())
  {
   System.out.println("路径或文件不存在");
   return;
  }
  if(filePath.length()>50*1024*1024){
   System.out.println("文件键过大");
   return ;
  }
  
  //建立客户端
  
  Socket client=null;
  BufferedInputStream bisPicture=null;
  try {
   //建立客户端
   client = new Socket(InetAddress.getLocalHost(),10001);
    //获取流 并装饰
   InputStream in=client.getInputStream();
   BufferedOutputStream bos=new BufferedOutputStream(client.getOutputStream());
   //读取本地需要上传的文件的流
   bisPicture = new BufferedInputStream(new FileInputStream(filePath));
   
   //先把文件的名字给服务端 \r\n是结束标记
   bos.write((fileName+"\r\n").getBytes());
   bos.flush();//穿了名字 立即刷新
   int len=0;//然后开始上传文件
   while((len=bisPicture.read())!=-1){
   
    //我要问的问题就在这里
   
    System.out.print("");//这里我不知道是什么原因 把这行注释了 就不能上传成功了 服务端存储的文件是没有内容的文件
    bos.write(len);
   }
   bos.flush();
   //标记
   client.shutdownOutput();
   //读取服务端的反馈信息 并打印
   byte[] buf=new byte[1024];
   int l=in.read(buf);
   System.out.println(new String(buf,0,l));
   
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{//关流
   try {
    if(client!=null)
    client.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }try {
    if(bisPicture!=null)
    bisPicture.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
}
}

class Servers{
public static void main(String args[]){
  //服务端
  ServerSocket server = null;
  
  try {
   server = new ServerSocket(10001,50);
   while(true)
   {
    final Socket s =  server.accept();//阻塞方法
    //为每一个客户端分配一个线程
    Executors.newSingleThreadExecutor().execute(new Runnable(){
     public void run(){
      BufferedOutputStream bosFile= null;
      //用来读取名字
       Reader reader =null;
      
      try {
       reader=new InputStreamReader(s.getInputStream());
      } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      }//读取流
      //获取客户端文件名
      char[] buf = new char[1024];
      String fileName=null;
      int ln=0;
      int count1 = 0;
      try {
       while((ln=reader.read())!=-1){
        if(ln=='\r'){
         continue;
        }
        if(ln=='\n'){
         break;
        }
        buf[count1]=(char) ln;
        count1++;
       }
       //得到了名字
       fileName = new String(buf,0,count1);
      } catch (IOException e1) {
       // TODO Auto-generated catch block
       e1.printStackTrace();
      }
      //分解文件名获取去后缀名 和文件名
      int lastPoint = fileName.lastIndexOf(".");
      String postfix = fileName.substring(lastPoint);
      String name = fileName.substring(0,lastPoint);
      
      //获取客户端主机名
      String clientName = s.getLocalAddress().getHostName();
      System.out.println(clientName+"    connection......");//打印连接了
      
      File fileDir = new File("D:\\javatemp");//上传文件存储的目录
      File filePath = new File(fileDir,fileName);//完整的路径名
      //上传同名文件时防止被覆盖
      int count = 1;
      if(filePath.exists())
      {
        filePath = new File(fileDir,name+"("+count+")"+postfix);
      }while(filePath.exists())
      {
       filePath = new File(fileDir,name+"("+ ++count +")"+"."+postfix);
      }
      try {
      
       //存储上传文件的输出流
       bosFile = new BufferedOutputStream(new FileOutputStream(filePath));
       int len= 0;
       //读取客户端上传数据
       BufferedInputStream bis=new BufferedInputStream(s.getInputStream());
       while((len=bis.read())!=-1)
       {
        bosFile.write(len);
       }
       bosFile.flush();
       s.getOutputStream().write("文件已上传".getBytes());
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } finally{
       try {
        if(bosFile!=null)
        bosFile.close();
       } catch (IOException e) {
        e.printStackTrace();
       }try {
        s.close();
       } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     }
    });
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}
}

点评

注意 提问时题目写详细些,代码最好写在代码区域里  发表于 2014-5-19 15:44

1 个回复

正序浏览
您需要登录后才可以回帖 登录 | 加入黑马