首先呢看一下需求吧:将A 电脑 d 盘的 文件 下载 到 B 电脑 的E盘 根目录 。因为小编只有一台电脑,所以也只能从简,但是思路都是一样的。不多说,程序献上:
客户端程序:
package com.liubo;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Socket socket=new Socket("localhost",6667);
OutputStream os = socket.getOutputStream();//网卡流
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("h:/books.xml");
byte [] b = new byte[1024];
int len = 0;
while( (len=is.read(b))!= -1 ){
fos.write(b, 0, len);
}
fos.close();
is.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
服务器端:
package com.liubo;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServiceDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket ss=null;
Socket socket=null;
try {
ss=new ServerSocket(6667);
socket=ss.accept();
InputStream is=socket.getInputStream();
OutputStream os = socket.getOutputStream();
//读取内容
byte [] b = new byte[1024];
int len = 0;
FileInputStream fis = new FileInputStream("D:/books.xml");
while( (len=fis.read(b))!= -1 ){
os.write(b, 0, len);
}
os.close();
fis.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
热门评论
值得看,对我帮助很大。