Java复制文件--客户端向服务端传输多个文件

最近写了一个复制文件小案例:Java复制文件--客户端向服务端传输多个文件


好久没有写这样子的小东西,写这个案例的原因是为了后面我做的东西做的一个tool工具类
代码比较简单 优化不是很多,注释我就少些了
客户端:

package com.teahel.Utils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Theahel
 * User: Matthew
 * Date: 2019/3/24
 * Time: 0:49
 * Description: 向服务端发送多个文件
 */
public class SupperClient extends Socket {
    private static final  String SERVER_IP="127.0.0.1";//服务器ip
    private static  final int SERVER_PORT=1996;//服务器端端口

    ExecutorService executorService = Executors.newCachedThreadPool();
  /*  public SupperClient()throws Exception{
        super(SERVER_IP,SERVER_PORT);
        this.client=this;
        System.out.println("Client[port:"+client.getLocalPort()+"]成功连接服务器");
    }*/




    public void sendFile() throws  Exception{

        try{
            File temp=null;
            File file=new File("D:\\PrjectTestFile\\test1");
            File files[] =file.listFiles();

            for(int i=0;i<files.length;i++){
                if(files[i].isFile()){
                   // doTran(files[i]);
                    executorService.execute(tranSomething(files[i]));
                }
                if(files[i].isDirectory()){
                    queryFile(file.getAbsolutePath()+File.separator+files[i].getName());

                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void queryFile(String directory){
        File tempFile=null;
        File file=new File(directory);
        File all[]=file.listFiles();
        for(int i=0;i<all.length;i++){
            if(all[i].isFile()){
                //doTran(all[i]);
                executorService.execute(tranSomething(all[i]));
            }
            if(all[i].isDirectory()){
                queryFile(directory+File.separator+all[i].getName());
            }

        }
    }
/*
    public void doTran(File file){
        try{
            if(file!=null){
                if(file.exists()){
                    fis=new FileInputStream(file);
                    dos=new DataOutputStream(client.getOutputStream());

                    //文件名和长度
                    dos.writeUTF(file.getName());
                    dos.flush();
                    dos.writeLong(file.length());
                    dos.flush();

                    //开始传输文件
                    System.out.println("---------开始传输文件-------------");
                    byte[] bytes=new byte[1024];
                    int length=0;
                    long progress=0;
                    while ((length=fis.read(bytes,0,bytes.length))!=-1){
                        dos.write(bytes,0,length);
                        dos.flush();
                        progress +=length;
                        System.out.println("|"+(100*progress/file.length())+"%|");
                    }
                    System.out.println();
                    System.out.println("==============文件传输成功=============");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(fis!=null){
                    fis.close();
                }
                if(dos!=null){
                    dos.close();
                    client.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }


    }*/


   private static Runnable tranSomething(final File file){
        return new Runnable() {
            private Socket client;
            private FileInputStream fis;
            private DataOutputStream dos;
            @Override
            public void run() {
                try{
                    if(file!=null){
                        if(file.exists()){
                            if(Connection()){
                                fis=new FileInputStream(file);
                                dos=new DataOutputStream(client.getOutputStream());

                                //文件名和长度
                                dos.writeUTF(file.getName());
                                dos.flush();
                                dos.writeLong(file.length());
                                dos.flush();

                                //开始传输文件
                                System.out.println("---------开始传输文件-------------");
                                byte[] bytes=new byte[1024];
                                int length=0;
                                long progress=0;
                                while ((length=fis.read(bytes,0,bytes.length))!=-1){
                                    dos.write(bytes,0,length);
                                    dos.flush();
                                    progress +=length;
                                    System.out.println("|"+(100*progress/file.length())+"%|");
                                }
                                System.out.println();
                                System.out.println("==============文件传输成功=============");
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try{
                        if(fis!=null){
                            fis.close();
                        }
                        if(dos!=null){
                            dos.close();
                            client.close();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
            }

            public boolean Connection()  {
                try{
                    client =new Socket(SERVER_IP,SERVER_PORT);
                    return  true;
                }catch (Exception e)
                {
                    return false;
                }
            }
        };
   }




    public static void main (String []args){
        try{
            SupperClient client =new SupperClient();
            client.sendFile();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

服务端

package com.teahel.Utils;

import javafx.concurrent.Task;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.RoundingMode;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;

/**
 * Created by Theahel
 * User: Matthew
 * Date: 2019/3/23
 * Time: 23:27
 * Description: 服务器类型
 */
public class Server extends ServerSocket {
    private static final int SERVER_PORT=1996;//服务器端口
    private static DecimalFormat df=null;

    static {
        df=new DecimalFormat("#0.0");//格式化 保留一位小数
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }
    public Server() throws Exception{
        super(SERVER_PORT);
    }

    public void  load()throws  Exception{
        while (true){
            Socket socket=this.accept();
            new Thread(new Task(socket)).start();
        }
    }

    class Task implements Runnable{
        private Socket socket;
        private DataInputStream dis;
        private FileOutputStream fos;

        public Task(Socket socket){
            this.socket=socket;
        }
        public void run(){
            try {
                dis=new DataInputStream(socket.getInputStream());

                //文件名和长度
                String fileName =dis.readUTF();
                long fileLength=dis.readLong();
                File direcory=new File("D:\\PrjectTestFile\\test2");
                if(!direcory.exists()){
                    direcory.mkdirs();
                }
                File file=new File(direcory.getAbsolutePath()+File.separator+fileName);
                fos=new FileOutputStream(file);

                //开始接收文件
                byte []bytes =new byte[1024];
                int length=0;
                while ((length=dis.read(bytes,0,bytes.length))!=-1){
                    fos.write(bytes,0,length);
                    fos.flush();
                }
                System.out.println("==============文件接收成功[file Name:"+fileName+"][Size :"+getFormatFileSize(fileLength));
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try{
                    if(fos!=null){
                        fos.close();
                    }
                    if(dis!=null){
                        dis.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        }
    }

    //文件大小
    private String getFormatFileSize(long length){
        double size =((double)length)/(1<<30);
        if(size>=1){
            return df.format(size)+"GB";
        }
        size=((double)length)/(1<<20);
        if(size>=1){
            return  df.format(size)+"MB";
        }
        size=((double)length)/(1<<10);
        if(size>=1){
            return  df.format(size)+"KB";
        }
        return length+"B";
    }

    public  static void main (String args[]){
     try{
        Server server=new Server();
        server.load();
     }catch (Exception e){
        e.printStackTrace();
     }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值