使用socket实现文件复制
网络编程之文件长传下载:
客户端:uploadClient.java:
package fileupload; import java.awt.image.BufferedImageFilter; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; /** * * @author superdrew * */ public class UploadClient { public static void main(String[] args) throws UnknownHostException, IOException { //1.创建socket 与 server进行连接 Socket socket = new Socket(InetAddress.getLocalHost(), 8888); //2.读取本地文件 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:/JDK_API_1_6_zh_CN.CHM")); //3.写入到网络中 BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); //读取并写入到网络 中转站 byte [] buf = new byte [1024]; int len = 0; while( ( len = bis.read(buf))!=-1 ){ //往网络中写 bos.write(buf,0,len); //再次读取文件 //len = bis.read(buf); } //4.关闭资源 bos.close(); bis.close(); } }
服务端:UploadServer.java:
package fileupload; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; /** * 使用socket完成文件复制 * 使用 tcp * udp 没有相关的IO流操作 * 之间讲的文件复制 单机 只能本地到本地 * * @author superdrew * */ public class UploadServer { public static void main(String[] args) throws IOException { //1.创建server ServerSocket server = new ServerSocket(8888); //2.监听 Socket socket = server.accept(); //3.通过socket读取网络文件 /*InputStream in = socket.getInputStream(); BufferedInputStream bis = new BufferedInputStream(in);*/ BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); //4.写入到本地文件 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:/JDK_API_1_6_zh_CN2.CHM")); //5.边读边写 //读取的中转站 byte [] buf = new byte [1024]; int len = 0; //len = bis.read(buf); while((len = bis.read(buf))!=-1){//组合式写法 //写入到文件 bos.write(buf, 0, len); //再次读取 //len = bis.read(buf); } //关闭流 bos.close(); bis.close(); } }