最佳答案:
準備條件:java實現ftp上傳用到了commons-net-3.3.jar包
首先建立ftphost連接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public boolean connect(String path, String addr, int port, String username, String password) { try { //FTPClient ftp = new FTPHTTPClient(addr, port, username, password); ftp = new FTPClient(); int reply; ftp.connect(addr); System.out.println( "連接到:" + addr + ":" + port); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println( "FTP目標服務器積極拒絕." ); System.exit( 1 ); return false ; } else { ftp.login(username, password); ftp.enterLocalPassiveMode(); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); ftp.changeWorkingDirectory(path); System.out.println( "已連接:" + addr + ":" + port); return true ; } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); return false ; } } |
然后再利用ftpclient的makeDirectory方法創建文件夾
1
2
3
4
5
6
7
8
|
public void createDir(String dirname){ try { ftp.makeDirectory(dirname); System.out.println( "在目標服務器上成功建立了文件夾: " + dirname); } catch (Exception ex){ System.out.println(ex.getMessage()); } } |
斷開host連接
1
2
3
4
5
6
7
|
public void disconnect(){ try { ftp.disconnect(); } catch (IOException e) { e.printStackTrace(); } } |
最后是程序的調用方法
1
2
3
4
5
6
7
|
public static void main(String[] args) { FtpUploadTest ftpupload = new FtpUploadTest(); if (ftpupload.connect( "" , "172.39.8.x" , 20 , "administrator" , "abc@123" )){ ftpupload.createDir( "/UPLOAD" ); ftpupload.disconnect(); } } |
其他回答:
首先保證ftp服務器的創建文件夾權限已開放,關鍵代碼如下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/** * 在當前目錄下創建文件夾 * * @param dir * @return * @throws Exception */ private boolean createDir(String dir) { try { ftpClient.ascii(); StringTokenizer s = new StringTokenizer(dir, "/" ); // sign s.countTokens(); String pathName = ftpClient.pwd(); while (s.hasMoreElements()) { pathName = pathName + "/" + (String) s.nextElement(); try { ftpClient.sendServer( "MKD " + pathName + "\r\n" ); } catch (Exception e) { e = null ; return false ; } ftpClient.readServerResponse(); } ftpClient.binary(); return true ; } catch (IOException e1) { e1.printStackTrace(); return false ; } } |
其他回答2:
用ftp命令:mkdir()
可以創建文件夾。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。