700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Java实现FTP点对点传输文件

Java实现FTP点对点传输文件

时间:2019-09-17 14:09:45

相关推荐

Java实现FTP点对点传输文件

Java实现C/S结构的FTP点对点传输文件,写成了服务端和客户端的形式:先来看Server端的代码是如何写的:

01packageftp2;

02importjava.io.*;

.*;

04publicclassServerFTP {

05intport=8083;

06String filepath="D:\\123.txt";

07voidstart(){

08Socket s=null;

09try{

10ServerSocket ss=newServerSocket(port);

11while(true){

12File file=newFile(filepath);

13if(!file.exists()){

14file.createNewFile();

15}

16System.out.println("文件长度:"+(int)file.length());

17s=ss.accept();

18System.out.println("建立socket连接");

19DataInputStream dis=newDataInputStream(newBufferedInputStream(newFileInputStream(filepath)));

20DataOutputStream dos=newDataOutputStream(s.getOutputStream());

21dos.writeUTF(file.getName());

22dos.writeLong((long)file.length());

23intbufferSize=8192;

24byte[] buf=newbyte[bufferSize];

25while(true){

26intread=0;

27if(dis!=null){

28read=dis.read(buf);

29}

30if(read==-1){

31break;

32}

33dos.write(buf,0,read);

34}

35dis.close();

36s.close();

37System.out.println("文件传输完毕!!");

38}

39}catch(Exception e) {

40e.printStackTrace();

41}

42}

43publicstaticvoidmain(String[] args) {

44newServerFTP().start();

45}

46}

再来看下Client客户端文件的代码:

view source

print?

01packageftp2;

02importjava.io.*;

.*;

04publicclassClientFTP {

05privateSocket s=null;

06privateString ip="localhost";

07privateintport=8082;

08publicClientFTP() {

09creationConnection();

10}

11privatevoidcreationConnection() {

12try{

13s=newSocket(ip,port);

14}catch(Exception e) {

15// TODO: handle exception

16}

17}

18privatevoidgetFile() {

19String savePath="I:\\";

20intbufferSize=8193;

21byte[] buf=newbyte[bufferSize];

22intpassedlen=0;

23longlength=0;

24try{

25DataInputStream dis=newDataInputStream(newBufferedInputStream(s.getInputStream()));

26savePath+=dis.readUTF();

27DataOutputStream dos=newDataOutputStream(newBufferedOutputStream(newFileOutputStream(savePath)));

28length=dis.readLong();

29System.out.println("文件长度:"+length+"\n");

30while(true) {

31intread=0;

32if(dis!=null){

33read=dis.read(buf);

34}

35passedlen+=read;

36if(read==-1) {

37break;

38}

39dos.write(buf,0,read);

40}

41System.out.println("接收文件另存为:"+savePath+"\n");

42dos.close();

43}catch(Exception e) {

44// TODO: handle exception

45}

46}

47publicstaticvoidmain(String[] args) {

48newClientFTP().getFile();

49}

50}

分别将上述两段代码保存为ServerFTP.java、ClientFTP.java,可在编译器中运行生成文件。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。