mac中的大文件拷贝到windows

关于java web应用的文件上传下载,有很多文章。我也写了一些,比如文件跨域传输 。我也写了一个web的工具,用来在不同机器间传输文件。

最近我想把mac上的电影拷到windows上,这里就有这个问题了。最简单靠谱的方式就是拿足够大的移动硬盘,一下子拷过去。但事与愿违,mac可以识别移动硬盘,但不能写入。

那么就用u盘吧,之前我为了让windows与mac都能识别u盘,特地把我的u盘格式化为了exFAT格式(mac与window都能识别的文件格式)。拷了几个电影又出问题了,这个文件系统不支持4G以上的文件。好吧,java代码上吧,用网络。

客户器端(mac,电影文件原始位置):

package com.highersoft.file;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.Socket;
import java.util.Calendar;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class FileTransferClient extends Socket {
	private static Log log=LogFactory.getLog(FileTransferClient.class);
	private static final String SERVER_IP = "192.168.0.104"; // 服务端IP
	private static final int SERVER_PORT = 8899; // 服务端端口
	private static final String filePath="/Users/chengzhong/Downloads/人间.空间.时间和人.Human.Space.Time.and.Human.2018.BD720P.HEVC.AAC.Korean.CHS/人间.空间.时间和人.Human.Space.Time.and.Human.2018.BD720P.HEVC.AAC.Korean.CHS.mkv";

	private Socket client;

	private FileInputStream fis;

	private DataOutputStream dos;

	/**
	 * 构造函数<br/>
	 * 与服务器建立连接
	 * 
	 * @throws Exception
	 */
	public FileTransferClient() throws Exception {
		super(SERVER_IP, SERVER_PORT);
		this.client = this;
		System.out.println("Cliect[port:" + client.getLocalPort() + "] 成功连接服务端");
	}

	/**
	 * 向服务端传输文件
	 * 
	 * @throws Exception
	 */
	public void sendFile() throws Exception {
		try {
			File file = new File(filePath);
			if (file.exists()) {
				fis = new FileInputStream(file);
				dos = new DataOutputStream(client.getOutputStream());

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

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

	/**
	 * 入口
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			FileTransferClient client = new FileTransferClient(); // 启动客户端连接
			client.sendFile(); // 传输文件
		} catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}
服务器端,(windows,电影文件目标位置):

package com.highersoft.file;

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;

public class FileTransferServer extends ServerSocket {
 
    private static final int SERVER_PORT = 8899; // 服务端端口
 
    private static DecimalFormat df = null;
 
    static {
        // 设置数字格式,保留一位有效小数
        df = new DecimalFormat("#0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }
 
    public FileTransferServer() throws Exception {
        super(SERVER_PORT);
    }
 
    /**
     * 使用线程处理每个客户端传输的文件
     * @throws Exception
     */
    public void load() throws Exception {
        while (true) {
            // server尝试接收其他Socket的连接请求,server的accept方法是阻塞式的
            Socket socket = this.accept();
            /**
             * 我们的服务端处理客户端的连接请求是同步进行的, 每次接收到来自客户端的连接请求后,
             * 都要先跟当前的客户端通信完之后才能再处理下一个连接请求。 这在并发比较多的情况下会严重影响程序的性能,
             * 为此,我们可以把它改为如下这种异步处理与客户端通信的方式
             */
            // 每接收到一个Socket就建立一个新的线程来处理它
            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;
        }
 
        @Override
        public void run() {
            try {
                dis = new DataInputStream(socket.getInputStream());
 
                // 文件名和长度
                String fileName = dis.readUTF();
                long fileLength = dis.readLong();
                File directory = new File("/Users/chengzhong/work_tool_install/filemanager/tmp");
                if(!directory.exists()) {
                    directory.mkdir();
                }
                File file = new File(directory.getAbsolutePath() + File.separatorChar + 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();
                    socket.close();
                } catch (Exception e) {}
            }
        }
    }
 
    /**
     * 格式化文件大小
     * @param length
     * @return
     */
    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";
    }
 
    /**
     * 入口
     * @param args
     */
    public static void main(String[] args) {
        try {
            FileTransferServer server = new FileTransferServer(); // 启动服务端
            server.load();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

有人可能会问,为什么不用java web的上传功能呢?

其实我尝试了,主要是在tomcat下的上传,有些弊端。小文件还好,一下子就传上去了,而几个G的文件,就要等很久。这个过程是个黑盒,是客户端到tomcat,tomcat封装为request对象里的File对象的过程。我们写的程序监控不到这个漫长的过程,看不到进度,让人怀疑程序出问题了,当然本来也可能出现内存溢出等问题。


文/程忠 浏览次数:0次   2020-08-10 07:42:03

相关阅读


评论:
点击刷新

↓ 广告开始-头部带绿为生活 ↓
↑ 广告结束-尾部支持多点击 ↑