上传端/客户端
import java. io. *;
import java. net. Socket;
public class Client {
private static final String HOST = "localhost" ;
private static final int PORT = 1721 ;
public void upFile ( String fileName) {
try {
Socket socket = new Socket ( HOST, PORT) ;
File file = new File ( fileName) ;
System. out. println ( "文件长度:" + ( int ) file. length ( ) ) ;
DataInputStream fileIn = new DataInputStream ( new FileInputStream ( fileName) ) ;
DataOutputStream out = new DataOutputStream ( socket. getOutputStream ( ) ) ;
byte [ ] buf = new byte [ 1024 ] ;
while ( ( fileIn. read ( buf) ) != - 1 ) {
out. write ( buf, 0 , buf. length) ;
}
out. flush ( ) ;
fileIn. close ( ) ;
out. close ( ) ;
socket. close ( ) ;
System. out. println ( "文件传输完成" ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static void main ( String[ ] args) {
Client client = new Client ( ) ;
client. upFile ( "src\\test.txt" ) ;
}
}
下载端/服务端
import java. io. *;
import java. net. ServerSocket;
import java. net. Socket;
public class Server {
private static final int PORT= 1721 ;
public void downFile ( String fileName) {
try {
ServerSocket serverSocket = new ServerSocket ( PORT) ;
Socket socket = serverSocket. accept ( ) ;
System. out. println ( "建立socket链接" ) ;
DataInputStream inputStream = new DataInputStream ( new BufferedInputStream ( socket. getInputStream ( ) ) ) ;
byte [ ] buf = new byte [ 1024 ] ;
DataOutputStream fileOut = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( fileName) ) ) ;
System. out. println ( "开始接收文件!" + "\n" ) ;
while ( ( inputStream. read ( buf) ) != - 1 ) {
fileOut. write ( buf, 0 , buf. length) ;
}
System. out. println ( "接收完成,文件存为" + fileName) ;
fileOut. close ( ) ;
} catch ( Exception e) {
System. out. println ( "接收消息错误" ) ;
e. printStackTrace ( ) ;
return ;
}
}
public static void main ( String[ ] args) {
Server server= new Server ( ) ;
server. downFile ( "src\\copy.txt" ) ;
}
}