关于获取远程文件的程序1:http://blog.csdn.net/notruiyi/archive/2005/10/22/513573.aspx
使用socket获取远程文件,要求本地和远程主机都打开端口,所以一般程序都会给出服务器端和客户端
1服务器端
--------------------------------------------------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
public class FileServer{
private int port = 3000;
//接收连接
public void acceptConnections(){
try{
ServerSocket server = new SocketServer(port);
Socket incomingSocket = null;
while(true){
incomingSocket = server.accept();
handleConnections(incomingSocket);
}
}catch(BindException e){
System.out.println("BindException occured.");
}catch(IOException e){
System.out.println("ServerSocket establish error.");
}
}
//处理连接
public void handleConnecitons(Socket socket){
try{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader outputReader = new BufferReader(new OutputStreamReader(socket.getOutputStream()));
//获取要读取的文件名
FileReader fileReader = new FileReader(new File(inputReader.readLine()));
BufferedReader bufferedFileReader = new BufferReader(fileReader);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
String line = null;
While((line = bufferFileReader.readLine())!=null)
printWriter.println(line);
fileReader.close();
printWriter.close();
outputReader.close();
}catch(Exception e){
System.out.println("Exception occured when handiling a client connection.");
}
}
}
2.客户端
-----------------------------------------------------------------------------------------------------------------
import java.io.*;
import java.net.*;
public class RemoteFileClient{
private String hostIP;
private int hostPort;
private BufferedReader socketReader;
private PrintWriter socketWriter;
public RemoteFileClient(String hostIP,int port ){
this.hostIP = hostIP;
this.port = port;
}
//启动连接
public void setupConnection(){
try{
Socket client = new Socket(hostip,port);
socketReader = new BufferReader(new InputStreamReader(client.getInputStream()));
socketWriter = new PrintWriter(client.getOutputStream());
}catch(UnknownHostException e){
System.out.println("Unkown host IP.");
}catch(IOException e){
System.out.println("Setting up connection error.");
}
}
//获取文件
public String getFile(String filename){
StringBuffer content = new StringBuffer();
try{
socketWriter.println(filename);
socketWriter.flush();
String line = null;
while((line = socketReader.readLine())!=null)
content.append(line+"\n");
}catch(IOException e){
System.out.println("Error on reading file.");
}
return content.toString();
}
//关闭连接
public void tearDownConnection(){
try{
socketReader.close();
socketWriter.close();
}catch(IOException e){
System.out.println("error on closeing socket connectiong.");
}
}
}