1.直接用SOCKET实现
server端:
package com.taobao.terminator.allen.shellTest; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class EcrmFileServerAllen { private final static int port = 18110; private final static int SIZE = 8192; private String basePath = "/home/admin/allen/file"; // private String basePath = "d:/test"; private void send(){ /** * 1.发送FileList * 2.接收FileName * 3.传递stream * 4.接收end,结束传递 */ ServerSocket server = null; Socket socket = null; DataInputStream fileIn = null; DataOutputStream out = null; DataInputStream in =null; try { server = new ServerSocket(port); File files = new File(basePath); socket = server.accept(); out = new DataOutputStream(socket.getOutputStream()); in = new DataInputStream(socket.getInputStream()); StringBuilder builder = new StringBuilder(); for(String s : files.list()){ builder.append(s); builder.append(","); } System.out.println("------------send file------------"); out.writeUTF(builder.toString()); out.flush(); while(true){ System.out.println("------------begin read file------------"); String fileName = in.readUTF(); System.out.println("read file : " + fileName); if("EOF".equals(fileName)){ System.out.println(fileName + "file send over ,thanks"); break; } File file = constuctNewFile(files.getAbsolutePath(),fileName); fileIn = new DataInputStream(new FileInputStream(file)); System.out.println("the file: " + fileName + "length is " + file.length()); out.writeLong(file.length()); out.flush(); byte[] buffer = new byte[SIZE]; while(true){ int read = 0; if(fileIn != null){ read = fileIn.read(buffer); } if ( read != -1){ out.write(buffer, 0, read); } else { break; } } System.out.println("Write file over: " + fileName); out.flush(); fileIn.close(); fileIn = null; } System.out.println("All is over"); } catch (IOException e) { throw new RuntimeException("IO传输异常",e); } finally{ try { out.close(); socket.close(); server.close(); } catch (IOException e) { throw new RuntimeException("IO关闭异常",e); } } } private File constuctNewFile(String filePath , String fileName){ fileName = filePath + File.separator + fileName; return new File(fileName); } public static void main(String arg[]) { PrintStream myout = null; try { myout = new PrintStream(new FileOutputStream(new File("/home/admin/main.log"))); } catch (FileNotFoundException e) { e.printStackTrace(); } System.setOut(myout); System.setErr(myout); new EcrmFileServerAllen().send(); } }
client端:
package com.taobao.terminator.allen.shellTest; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; public class EcrmFileClientAllen { private final static int port = 18110; private final static int SIZE = 8192; private String basePath = "/home/admin/allen/file"; // private String basePath = "c:/test"; private DataInputStream in = null; private DataOutputStream out = null; private DataOutputStream fileOut = null; private void receive(String host){ System.out.println("***********start**********"); try { Socket socket = new Socket(host, port); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream( socket.getOutputStream()) ; String fileNames = in.readUTF(); String[] files = fileNames.split(","); System.out.println("---------Read files------------"); try { for (String fileName : files) { System.out.println("the file is :" + fileName); out.writeUTF(fileName); out.flush(); long length = in.readLong(); System.out.println("the file length is :" + length); int slength = 0; File file = new File(this.basePath + File.separator + fileName); fileOut = new DataOutputStream(new FileOutputStream(file)); System.out.println("begin copy :" + file); int read = 0; boolean mark = true; while (mark) { System.out.println("开始读字节流:" + file.getName() + "此时:" + mark); byte[] b = new byte[SIZE]; if ((read = in.read(b)) != -1) { System.out.println("读取大小:" + read); fileOut.write(b, 0, read); System.out.println("写文件:" + file.getAbsolutePath()); slength += read; System.out.println("length:" + length + ": slength" + slength); if(slength == length){ mark = false; System.out.println("文件读完了:" + file.getName()); } } } System.out.println("end copy :" + fileName); } out.writeUTF("EOF"); out.flush(); } finally { System.out.println("执行finally"); in.close(); out.close(); socket.close(); } System.out.println("******one file ok*********"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String arg[]) { PrintStream myout = null; try { myout = new PrintStream(new FileOutputStream(new File("/home/admin/main.log"))); } catch (FileNotFoundException e) { e.printStackTrace(); } System.setOut(myout); System.setErr(myout); new EcrmFileClientAllen().receive("10.232.37.56"); } }
2.用ServerSocektChannel实现
server端:
package com.taobao.terminator.allen.shellTest; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; public class ChannelFileServerAllen { private final static int SIZE = 1024 * 1024 * 1; private final static String filepath = "d://test"; public static void main(String[] args) { ServerSocketChannel serverChannel = null; InetSocketAddress host = null; SocketChannel channel = null; try { serverChannel = ServerSocketChannel.open(); host = new InetSocketAddress("localhost", 11100); serverChannel.socket().bind(host); channel = serverChannel.accept(); //传输文件名 StringBuilder builder = new StringBuilder(); File files = new File(filepath); String[] sfile = files.list(); for(int i = 0; i < sfile.length; i++){ builder.append(sfile[i]); if(i != sfile.length - 1) { builder.append(","); } } byte[] b = builder.toString().getBytes(); ByteBuffer buffer = ByteBuffer.wrap(b, 0, b.length); channel.write(buffer); buffer.clear(); //接收文件 while(true) { //获取传递文件名 buffer = ByteBuffer.allocate(SIZE); channel.read(buffer); buffer.clear(); byte[] newbyte = buffer.array(); String name =new String(newbyte); if (name.startsWith("END")) { break; } else { File newFile = new File(filepath, name); // 传输文件大小 buffer.clear(); buffer.putLong(newFile.length()); buffer.flip(); channel.write(buffer); //传输文件 ByteBuffer src = ByteBuffer.allocate(SIZE); FileChannel fChannel = new FileInputStream(newFile).getChannel(); while ((fChannel.read(src)) != -1 ) { src.flip(); channel.write(src); src.clear(); } fChannel.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (channel != null) { try { channel.close(); } catch (IOException e) { System.err.println(e); } } if (serverChannel != null) { try { serverChannel.close(); } catch (IOException e) { System.err.println(e); } } } } public static final String getLocalHostIP() { try { return InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { throw new RuntimeException("[local-ip] an exception occured when get local ip address", e); } } }
client端:
package com.taobao.terminator.allen.shellTest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; public class ChannelFileClientAllen { private final static int SIZE = 1024 * 1024 * 1 ; private final static String filePath = "c://test"; public static void main(String[] args) { SocketChannel channel = null; try { channel = SocketChannel.open(); channel.socket().bind(new InetSocketAddress(InetAddress.getLocalHost() ,0)); channel.connect(new InetSocketAddress("localhost" ,11100)); ByteBuffer buffer = ByteBuffer.allocate(SIZE); //读取文件名 String sfile = null; channel.read(buffer); buffer.clear(); byte[] bt = buffer.array(); sfile = new String(bt); String[] files = sfile.split(","); //获取文件 byte[] sb = null; for(String fileName : files) { File file = new File(filePath , fileName); if (!file.exists()) { file.createNewFile(); } else { file.delete(); } //传递文件名给server端 sb = fileName.getBytes(); buffer = ByteBuffer.wrap(sb, 0, sb.length); channel.write(buffer); buffer.clear(); FileChannel fChannel = new FileOutputStream(file).getChannel(); channel.read(buffer); long fileSize = buffer.getLong(0); long size = 0; int a = 0; while ((a = channel.read(buffer)) != -1) { buffer.flip(); fChannel.write(buffer); buffer.clear(); size += a; if(size == fileSize) { fChannel.close(); break ; } } } sb = "END".getBytes(); buffer = ByteBuffer.wrap(sb, 0, sb.length); channel.write(buffer); buffer.clear(); } catch (Exception e) { e.printStackTrace(); } finally { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } } }