客户端
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* 客户端
* @author
*
*/
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket = null;
File file = new File("D:\\c.txt");//保存的文件
FileOutputStream fout = null;
DataInputStream din = null;
byte[] outByte = new byte[1024];
int length = 0;
try {
socket = new Socket("127.0.0.1",5564);//接收的端口号
din = new DataInputStream(socket.getInputStream());
fout = new FileOutputStream(file);
while((length = din.read(outByte, 0, outByte.length)) != -1)
{
fout.write(outByte, 0, length);
fout.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
socket.close();
fout.close();
din.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
服务器端
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端
* @author
*
*/
public class Server {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server=null;
Socket socket=null;
DataOutputStream dout=null;
File file=new File("D:\\a.txt");//读取文件的地址
FileInputStream fin=null;
byte[]inByte=new byte[1024];
int length=0;
try {
server=new ServerSocket(5564);//服务器端口号
socket=server.accept();
dout=new DataOutputStream(socket.getOutputStream());
fin=new FileInputStream(file);
while((length=fin.read(inByte, 0, inByte.length))!=-1)//对文件的内容进行读取
{
dout.write(inByte, 0, length);
dout.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
server.close();
socket.close();
fin.close();
dout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}