Java实现C/S结构的FTP点对点传输文件,写成了服务端和客户端的形式:先来看Server端的代码是如何写的: 04 | public class ServerFTP { |
06 | String filepath= "D:\\123.txt" ; |
10 | ServerSocket ss= new ServerSocket(port); |
12 | File file= new File(filepath); |
16 | System.out.println( "文件长度:" +( int )file.length()); |
18 | System.out.println( "建立socket连接" ); |
19 | DataInputStream dis= new DataInputStream( new BufferedInputStream( new FileInputStream(filepath))); |
20 | DataOutputStream dos= new DataOutputStream(s.getOutputStream()); |
21 | dos.writeUTF(file.getName()); |
22 | dos.writeLong(( long )file.length()); |
24 | byte [] buf= new byte [bufferSize]; |
33 | dos.write(buf, 0 ,read); |
37 | System.out.println( "文件传输完毕!!" ); |
39 | } catch (Exception e) { |
43 | public static void main(String[] args) { |
44 | new ServerFTP().start(); |
再来看下Client客户端文件的代码: 04 | public class ClientFTP { |
05 | private Socket s= null ; |
06 | private String ip= "localhost" ; |
07 | private int port= 8082 ; |
11 | private void creationConnection() { |
13 | s= new Socket(ip,port); |
14 | } catch (Exception e) { |
15 | // TODO: handle exception |
18 | private void getFile() { |
19 | String savePath= "I:\\" ; |
21 | byte [] buf= new byte [bufferSize]; |
25 | DataInputStream dis= new DataInputStream( new BufferedInputStream(s.getInputStream())); |
26 | savePath+=dis.readUTF(); |
27 | DataOutputStream dos= new DataOutputStream( new BufferedOutputStream( new FileOutputStream(savePath))); |
28 | length=dis.readLong(); |
29 | System.out.println( "文件长度:" +length+ "\n" ); |
39 | dos.write(buf, 0 ,read); |
41 | System.out.println( "接收文件另存为:" +savePath+ "\n" ); |
43 | } catch (Exception e) { |
44 | // TODO: handle exception |
47 | public static void main(String[] args) { |
48 | new ClientFTP().getFile(); |
分别将上述两段代码保存为ServerFTP.java、ClientFTP.java,可在编译器中运行生成文件。
|