可以,例程如下
//客户端发送文件,使用命令行输入发送文件 TalkClient
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) {
try{
Socket socket=new Socket("127.0.0.1",4700);
BufferedReader sin=new BufferedReader(new FileReader(args[0]));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader( new InputStreamReader(socket.getInputStream()));
String readline;
readline=sin.readLine();
while(readline!=null)
{
os.println(readline);
os.flush();
//System.out.println("Server:"+is.readLine());
readline=sin.readLine();
}
os.close();
is.close();
socket.close();
}catch(Exception e) {
System.out.println("Error"+e);
}
}
}
//服务端接收文件 TalkServer.java
import java.io.*;
import java.net.*;
import java.applet.Applet;
public class TalkServer{
public static void main(String args[]) {
try{
ServerSocket server=null;
try{
server=new ServerSocket(4700);
}catch(Exception e) {
System.out.println("can not listen to:"+e);
}
Socket socket=null;
try{
socket=server.accept();
}catch(Exception e) {
System.out.println("Error."+e);
}
String readline;
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Client:"+is.readLine());
readline=is.readLine();
while(readline!=null)
{
System.out.println("Client:"+readline);
readline=is.readLine();
}
is.close();
socket.close();
server.close();
}catch(Exception e){
System.out.println("Error:"+e);
}
}
}