关闭ftp连接的最佳实践是什么?

gblwokeq  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(453)

我想避免system.exit(0),因为在我的程序中有一个调度程序每天都会启动这段代码。

  1. FTPClient client = new FTPClient();
  2. FileInputStream fis = null;
  3. try {
  4. System.out.println("Establishing connection...");
  5. client.connect(ftpHost, ftpPort);
  6. System.out.print(client.getReplyString());
  7. System.out.println("Connection ok.");
  8. if (client.login(ftpUser, ftpPass)) {
  9. System.out.println("Login ok");
  10. System.out.print(client.getReplyString());
  11. System.out.println("Setting PASV");
  12. client.enterLocalPassiveMode();
  13. System.out.print(client.getReplyString());
  14. } else {
  15. System.out.println("Login error!");
  16. System.out.print(client.getReplyString());
  17. }
  18. if (client.changeWorkingDirectory("/path/mydir")) {
  19. System.out.println("Dir changed");
  20. System.out.print(client.getReplyString());
  21. } else {
  22. System.out.println("Error changing dir");
  23. System.out.print(client.getReplyString());
  24. }
  25. //Upload
  26. fis = new FileInputStream("README.txt");
  27. if(client.storeFile("README.txt", fis))
  28. {
  29. System.out.println("File sent");
  30. System.out.print(client.getReplyString());
  31. }
  32. else
  33. {
  34. System.out.println("Error during sending file");
  35. System.out.print(client.getReplyString());
  36. }
  37. if (client.logout()) {
  38. System.out.println("Logout closed successfully");
  39. System.out.print(client.getReplyString());
  40. } else {
  41. System.out.println("Logout problem");
  42. System.out.print(client.getReplyString());
  43. }
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }

出了问题我要用什么?注销?断开连接?或者其他东西?

x4shl7ld

x4shl7ld1#

client.disconnect();就足够了:

  1. finally {
  2. if (client.isConnected()) {
  3. try {
  4. client.disconnect();
  5. } catch (IOException ioe) {
  6. // do nothing
  7. }
  8. }
  9. }

参见官方示例。

相关问题