<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Latest posts for the topic "JSP精選實用範例(四):檔案傳輸"]]></title>
		<link>http://www.andowson.com/posts/list/5.page</link>
		<description><![CDATA[Latest messages posted in the topic "JSP精選實用範例(四):檔案傳輸"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 預先安裝函式庫：[url=http://commons.apache.org/downloads/download_net.cgi]Apache Commons Net[/url]<br /> 程式碼： <br /> ftptest.jsp:<br /> [code]<br /> &lt;%@ page import="java.io.File"%&gt;<br /> &lt;%@ page import="java.io.FileInputStream"%&gt;<br /> &lt;%@ page import="java.io.FileOutputStream"%&gt;<br /> &lt;%@ page import="java.io.IOException"%&gt;<br /> &lt;%@ page import="org.apache.commons.net.ftp.FTP"%&gt;<br /> &lt;%@ page import="org.apache.commons.net.ftp.FTPClient"%&gt;<br /> &lt;%@ page import="org.apache.commons.net.ftp.FTPFile"%&gt;<br /> &lt;%@ page import="org.apache.commons.net.ftp.FTPReply"%&gt;<br /> &lt;%<br /> 	String server = "192.168.1.2";<br /> 	String username = "andowson";<br /> 	String password = "changeit";<br /> 	String directory = "download";<br /> 	String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";<br /> 	File filePut = new File(filename);<br /> 	String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";<br /> 	File fileGet = new File(filename2);<br /> 	String filename3 = "jdk-6u3-windows-i586-p.exe";<br /> 	<br /> 	FTPClient ftp = new FTPClient();<br /> 	// We want to timeout if a response takes longer than 30 seconds<br /> 	ftp.setDefaultTimeout(30000);<br /> 	try {<br /> 		int reply;<br /> 		ftp.connect(server);<br /> 		System.out.println("Connected to " + server + ".");<br /> 		System.out.print(ftp.getReplyString());<br /> <br /> 		// After connection attempt, you should check the reply code to verify<br /> 		// success.<br /> 		reply = ftp.getReplyCode();<br /> <br /> 		if (!FTPReply.isPositiveCompletion(reply)) {<br /> 			ftp.disconnect();<br /> 			System.err.println("FTP server refused connection.");<br /> 			return;<br /> 		}<br /> 		// transfer files<br /> 		if (ftp.login(username, password)) {<br /> 			long totalSize = 0L;<br /> 			for (FTPFile file : ftp.listFiles(directory)) {<br /> 				System.out.printf("%s %s [%d bytes]\n",<br /> 						(file.isDirectory() ? "[D]" : "   "), file.getName(), file.getSize());<br /> 				if (!file.isDirectory()) {<br /> 					totalSize += file.getSize();<br /> 				}<br /> 			}			<br /> 			System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");<br /> 			<br /> 			// PASV<br /> 			ftp.enterLocalPassiveMode();<br /> 			// CWD<br /> 			ftp.changeWorkingDirectory(directory);<br /> 			// PWD<br /> 			System.out.println(ftp.printWorkingDirectory());<br /> 			// TYPE I<br /> 			ftp.setFileType(FTP.BINARY_FILE_TYPE);			<br /> 			// PUT<br /> 			ftp.storeFile(filePut.getName(), new FileInputStream(filePut));<br /> 			// GET<br /> 			ftp.retrieveFile(fileGet.getName(), new FileOutputStream(fileGet));<br /> 			// DELE<br /> 			ftp.deleteFile(filename3);<br /> 		}<br /> 		ftp.logout();<br /> 	} catch (IOException e) {<br /> 		e.printStackTrace();<br /> 	} finally {<br /> 		if (ftp.isConnected()) {<br /> 			try {<br /> 				ftp.disconnect();<br /> 			} catch (IOException ioe) {<br /> 				// do nothing<br /> 			}<br /> 		}<br /> 	}<br /> %&gt;[/code]<br /> 參考資料：<br /> http://commons.apache.org/net/apidocs/index.html]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/303.page</guid>
				<link>http://www.andowson.com/posts/preList/199/303.page</link>
				<pubDate><![CDATA[Mon, 17 Dec 2007 23:56:38]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 預先安裝函式庫：[url=http://www.enterprisedt.com/products/edtftpj/downloadlink.html]edtFTPj/Free[/url]<br /> 程式碼：<br /> ftpdemo.jsp: <br /> [code]<br /> &lt;%@ page import="java.io.File"%&gt;<br /> &lt;%@ page import="java.util.Locale"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPClient"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPConnectMode"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPException"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPFile"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPMessageCollector"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPReply"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.FTPTransferType"%&gt;<br /> &lt;%@ page import="com.enterprisedt.net.ftp.UnixFileParser"%&gt;<br /> &lt;%<br /> 	// assign args to make it clear<br /> 	String server = "192.168.1.2";<br /> 	String username = "andowson";<br /> 	String password = "changeit";<br /> 	String directory = "download";<br /> 	String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";<br /> 	File filePut = new File(filename);<br /> 	String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";<br /> 	File fileGet = new File(filename2);<br /> 	String filename3 = "jdk-6u3-windows-i586-p.exe";<br /> <br /> 	FTPClient ftp = new FTPClient();<br /> 	// We want to timeout if a response takes longer than 30 seconds<br /> 	ftp.setTimeout(30000);<br /> <br /> 	try {<br /> 		// set up client    <br /> 		ftp.setRemoteHost(server);<br /> 		FTPMessageCollector listener = new FTPMessageCollector();<br /> 		ftp.setMessageListener(listener);<br /> <br /> 		// connect<br /> 		ftp.connect();<br /> 		System.out.println("Connected to " + server + ".");<br /> 		String messages = listener.getLog();<br /> 		System.out.print(messages);<br /> <br /> 		FTPReply reply = ftp.getLastReply();<br /> 		if (reply != null) {<br /> 			System.out.print(reply.getRawReply());<br /> 			//String replyCode = reply.getReplyCode();<br /> 			System.out.print(reply.getReplyCode());<br /> 		}<br /> <br /> 		// login<br /> 		ftp.login(username, password);<br /> <br /> 		// set up passive BINARY transfers<br /> 		ftp.setConnectMode(FTPConnectMode.PASV);<br /> 		// get directory and print it to console            <br /> 		UnixFileParser ufp = new UnixFileParser();<br /> 		ufp.setLocale(new Locale("en", "US"));<br /> 		String[] files = ftp.dir(directory, true);<br /> 		long totalSize = 0L;<br /> 		for (int i = 0; i &lt; files.length; i++) {<br /> 			//System.out.println(files[i]);<br /> 			FTPFile file = ufp.parse(files[i]);<br /> 			System.out.printf("%s %s [%d bytes]\n",<br /> 					(file.isDir() ? "[D]" : "   "), file.getName(),	file.size());<br /> 			if (!file.isDir()) {<br /> 				totalSize += file.size();<br /> 			}<br /> 		}<br /> 		System.out.println("totalSize = " + totalSize / (1024 * 1024) + "MB");<br /> 		ftp.chdir(directory);<br /> 		System.out.println(ftp.pwd());<br /> 		ftp.setType(FTPTransferType.BINARY);<br /> <br /> 		// copy file to server <br /> 		ftp.put(filename, filePut.getName());<br /> <br /> 		// copy file from server<br /> 		ftp.get(filename2, fileGet.getName());<br /> <br /> 		// delete file from server<br /> 		ftp.delete(filename3);<br /> <br /> 		// Shut down client                <br /> 		ftp.quit();<br /> 	} catch (FTPException e) {<br /> 		e.printStackTrace();<br /> 	} finally {<br /> 		if (ftp.connected()) {<br /> 			try {<br /> 				ftp.quit();<br /> 			} catch (Exception e) {<br /> 				// do nothing<br /> 			}<br /> 		}<br /> 	}<br /> %&gt;<br /> [/code]<br /> <br /> 備註：<br /> edtFTPj的函式名稱跟FTP指令的名稱相當接近，使用起來比較直覺，但39-44行部分印不出東西來，不知道為什麼抓不到replyCode，如果您有試出來，請告知一下。]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/304.page</guid>
				<link>http://www.andowson.com/posts/preList/199/304.page</link>
				<pubDate><![CDATA[Mon, 24 Dec 2007 00:11:08]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 不好意思請問一下  <br /> ftptest.jsp裡有這一行 [color=red]ftp.setDefaultTimeout(30000);[/color]<br /> 設定這時間是什麼意思?<br /> ]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/443.page</guid>
				<link>http://www.andowson.com/posts/preList/199/443.page</link>
				<pubDate><![CDATA[Tue, 26 Aug 2008 10:53:47]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ [quote=viva]不好意思請問一下  <br /> ftptest.jsp裡有這一行 [color=red]ftp.setDefaultTimeout(30000);[/color]<br /> 設定這時間是什麼意思?<br /> [/quote]<br /> 原來的程式碼上寫了：<br /> // We want to timeout if a response takes longer than [color=red]30 seconds[/color]   <br /> ftp.setDefaultTimeout(30000);<br /> 因為setDefaultTimeout(int timeout)裡面timeout的單位是milliseconds（千分之一秒），故我們要乘上1000，就變成30000。<br /> 至於為何要設定Timeout，是因為在建立TCP的socket連線時，需要等候連線的對方回應ACK，以確認對方還活著，而這個等候的時間就是Timeout的時間，超過這個時間，我們就認為對方掛了，這個connection就無法成功建立。]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/444.page</guid>
				<link>http://www.andowson.com/posts/preList/199/444.page</link>
				<pubDate><![CDATA[Tue, 26 Aug 2008 13:04:23]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 不好意思,在請教一下<br /> [color=red]ftp.setDefaultPort(21);[/color]<br /> 這語法的用意是什麼?為何會設21與13?<br /> 若不加這行,也OK嗎?]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/448.page</guid>
				<link>http://www.andowson.com/posts/preList/199/448.page</link>
				<pubDate><![CDATA[Tue, 2 Sep 2008 15:24:05]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ [quote=viva]不好意思,在請教一下<br /> [color=red]ftp.setDefaultPort(21);[/color]<br /> 這語法的用意是什麼?為何會設21與13?<br /> 若不加這行,也OK嗎?[/quote]<br /> 因為FTP通訊協定預設的通訊埠是21，而org.apache.commons.net.ftp.FTP.DEFAULT_PORT的值即為21，所以如果您要連的FTP Server沒有改過port號的話，不用加這一行也OK。<br /> 另外，我的範例程式中應該是沒加這一行，也沒看到什麼13的數字，所以我無法回答「為何會設21與13?」<br /> ]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/449.page</guid>
				<link>http://www.andowson.com/posts/preList/199/449.page</link>
				<pubDate><![CDATA[Tue, 2 Sep 2008 18:00:13]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 之前在Google找了一些FTP連線的資料<br /> 因看到有些範例會加那行...所以才不懂為何是21與13<br /> 不過現在了解了,感謝你的指導!!<br /> <br /> 在請教一下...(我好像問題好多,不知道會不會造成你困擾)<br /> 我已經寫好我自己要使用的FTP程式...<br /> 但....如果在FTP設定[color=red]伺服器種類[/color]設為[color=red]FTPES-透過外顯式TLS/SSL的FTP[/color]<br /> 那我的FTP程式還連的上嗎?]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/450.page</guid>
				<link>http://www.andowson.com/posts/preList/199/450.page</link>
				<pubDate><![CDATA[Tue, 2 Sep 2008 20:09:45]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ [quote=viva]<br /> 在請教一下...(我好像問題好多,不知道會不會造成你困擾)<br /> 我已經寫好我自己要使用的FTP程式...<br /> 但....如果在FTP設定[color=red]伺服器種類[/color]設為[color=red]FTPES-透過外顯式TLS/SSL的FTP[/color]<br /> 那我的FTP程式還連的上嗎?[/quote]<br /> <br /> 有問題互相討論是OK的，不過希望能提供較多的資訊，例如完整或部分的程式碼，這樣子別人對於您的問題的內容會比較清楚。<br /> 目前支援[url=http://en.wikipedia.org/wiki/FTPS]FTPS[/url]的Java FTP Library大多是commercial component，如[url=http://www.enterprisedt.com/products/edtftpjssl/overview.html]edtFTPj/Pro[/url]。所以您的程式需要換掉Library及修改部分程式碼才能連上。<br /> 我找到了一個FTPES的範例程式，網址如下：<br /> <a class="snap_shots" href="http://www.example-code.com/java/ftp_AuthSSL.asp" target="_blank" rel="nofollow">http://www.example-code.com/java/ftp_AuthSSL.asp</a><br /> 您可以參考，用到的元件下載網址如下：<br /> <a class="snap_shots" href="http://www.chilkatsoft.com/download/ChilkatJava.zip" target="_blank" rel="nofollow">http://www.chilkatsoft.com/download/ChilkatJava.zip</a>]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/451.page</guid>
				<link>http://www.andowson.com/posts/preList/199/451.page</link>
				<pubDate><![CDATA[Tue, 2 Sep 2008 22:03:24]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 程式碼裡呼叫了一些function,是自訂的!<br /> 原本用意是想[color=red]上傳某個檔案到A  SERVER[/color],再從[color=red]A  SERVER上傳到B SERVER[/color]<br /> 而以下程式就是做[color=red]從A  SERVER上傳到B SERVER[/color]<br /> 檔案下載沒用到,所以他把"罵克"起來<br /> <br /> 感謝andowson的指導,這支FTP程式學到了很多,謝謝! <br /> <br /> [code]&lt;%@ page contentType="text/html; charset=BIG5" %&gt;<br /> &lt;jsp:useBean id="dbOprBean" scope="page" class="com.gemmyplanet.dbbean.DBOperationBean" /&gt;<br /> &lt;jsp:setProperty name="dbOprBean" property="*" /&gt;	<br /> &lt;%@ include file="inc_common_parameters.jsp" %&gt;<br /> &lt;%@ include file="inc_common_fun_ecindp.jsp" %&gt;<br /> &lt;%@ include file="inc_common_fun_doc.jsp" %&gt;<br /> &lt;%@ include file="inc_gp_fun_mysql5.jsp" %&gt;<br /> &lt;%@ page import="java.io.*"%&gt;<br /> &lt;%@ page import="java.util.*"%&gt;<br /> &lt;%@ page import="org.apache.commons.net.ftp.*"%&gt;		<br /> &lt;%<br /> 	/////////////////////////////////////////////////<br /> 	// 接收參數<br /> 	//////////////////////////////////////////////////		<br /> 	String GPBID = null;<br /> 	try{<br /> 		GPBID = request.getParameter("GPBID");<br /> 		if( GPBID == null )<br /> 			gERR = 1;<br /> 	}catch(Exception e) {<br /> 		gERR = 1;<br /> 		gERRMSG = "lack parameter";	<br /> 	}<br /> <br /> 	/////////////////////////////////////////////////<br /> 	// 宣告參數<br /> 	//////////////////////////////////////////////////	<br /> 	String server = "主機名稱";			<br /> 	String login = "帳號";<br /> 	String password = "密碼";<br /> 	String Ftp_Upload_FileName = "";					//上傳檔名<br /> 	GPDatabaseTK gpdb = new GPDatabaseTK(dbOprBean, "BIG5");<br /> 	GPJAVATK gpjtk = new GPJAVATK(gpdb);	<br /> 		<br /> 	/////////////////////////////////////////////////<br /> 	// 取出檔名並重新命名<br /> 	//////////////////////////////////////////////////<br /> 	if( gERR == 0 ) {	<br /> 		BANNERINFO bannerinfo = gpjtk.getBannerFilename( GPBID );			//以 GPBID 抓 Banner 檔名<br /> 		if( bannerinfo != null ) {<br /> 			String[] tokens = (bannerinfo.mFILENAME).split("\\/");<br /> 			Ftp_Upload_FileName = tokens[(tokens.length)-1];<br /> 	<br /> 	/////////////////////////////////////////////////<br /> 	// 連接 FTP<br /> 	//////////////////////////////////////////////////	<br /> 			FTPClient ftp = new FTPClient();	                            //連接、登錄服務器<br /> 			ftp.setDefaultTimeout(30000); 		   							//等候連線的對方回應ACK的時間 <br /> 		    <br />             try {<br /> 				int reply;		<br /> 			 	String UploadCatalog = "/public_html/res";					//上傳到哪個目錄下/public_html/res<br /> 			  	ftp.setDefaultPort(21);<br /> 			 	ftp.connect( server );										//連接FTP<br /> 				ftp.login( login, password );								//登入<br /> 		      	ftp.changeWorkingDirectory( UploadCatalog ); 				//當下在 Ftp 服務器上的工作目錄         <br /> 				reply = ftp.getReplyCode();<br /> 				<br /> 				if ( !FTPReply.isPositiveCompletion(reply) ) {				//判斷是否連線成功?<br /> 					ftp.logout();											//退出 FTP 服務器 					<br /> 					ftp.disconnect();										//關閉連接<br /> %&gt;					&lt;script language=javascript&gt;<br /> 						window.alert("FTP連線失敗！");<br /> 						location.href="http://失敗後返回的網址";<br /> 					&lt;/script&gt;<br /> &lt;%						<br /> 				} else {<br /> /*			<br /> 			      	FTPFile[] list = ftp.listFiles();						//獲得當前 FTP 服務器工作目錄中的文件列表 <br /> 			      	for (int i = 0; i &lt; list.length; i++) {      		<br /> 			       		String name = list[i].getName();					//取得檔名<br /> 			        	out.println("FTP檔名  : " + name+"&lt;br&gt;");	    <br /> 			      	}<br /> */	      		<br /> 	/////////////////////////////////////////////////<br /> 	// 檔案上傳<br /> 	//////////////////////////////////////////////////	<br /> 			        try {<br /> 			        	int file_size; <br />                          //圖檔路徑 "C:/Program Files/Apache Group/Tomcat 4.1/webapps/gp_image/res/"+Ftp_Upload_FileName<br /> 						String path = gWEBROOT+"/gp_image/res/"+Ftp_Upload_FileName;		<br /> 			        	File file = new File(path);<br /> 			        	if( file.exists() ) {<br /> 				   			FileInputStream fis = new FileInputStream(file); <br /> 				            ftp.setBufferSize(1024); 		       <br /> 				            ftp.setFileType(ftp.BINARY_FILE_TYPE);			//設置文件類型(二進制)，圖檔都用BINARY_FILE_TYPE     						        	<br /> 							ftp.storeFile( Ftp_Upload_FileName , fis );<br /> 							fis.close();									//關閉串流<br /> 					<br /> 	/////////////////////////////////////////////////<br /> 	// 檔案下載<br /> 	//////////////////////////////////////////////////	<br /> /*					<br /> 							String remoteFileName = "/ftp_test/01.jpg"; <br /> 							File file = new File("c:/999999999.jpg");<br /> 				            FileOutputStream fos = new FileOutputStream(file); <br /> 				            ftp.setBufferSize(1024); <br /> 				            ftp.setFileType(ftp.BINARY_FILE_TYPE);			//設置文件類型(二進制)，圖檔都用BINARY_FILE_TYPE <br /> 				            ftp.retrieveFile(remoteFileName, fos);<br /> 				            fos.close();<br /> 				            if( file.exists() ) {<br /> 				            	out.println("檔案存在&lt;br&gt;");<br /> 				            } else {<br /> 				            	out.println("檔案不存在");<br /> 				            }<br /> */<br /> 					      	if (ftp != null && ftp.isConnected()) {<br /> 					          	ftp.logout();								//退出 FTP 服務器 <br /> 					          	ftp.disconnect();							//關閉連接<br /> 					      	} 	<br /> %&gt;							&lt;script language=javascript&gt;<br /> 								window.alert("上傳成功！");<br /> 								location.href="http://成功後返回的網址";<br /> 							&lt;/script&gt;<br /> &lt;%						} else {<br /> 					      	if (ftp != null && ftp.isConnected()) {<br /> 					          	ftp.logout();								//退出 FTP 服務器 <br /> 					          	ftp.disconnect();							//關閉連接<br /> 					      	} 	<br /> %&gt;							&lt;script language=javascript&gt;<br /> 								window.alert("檔案不存在！");<br /> 								location.href="http://返回網址";<br /> 							&lt;/script&gt;<br /> &lt;%						}	      <br /> 			        } catch (IOException e) {<br /> %&gt;						&lt;script language=javascript&gt;window.alert("FTP上傳失敗！&lt;%=e.getMessage()%&gt;！");&lt;/script&gt;			         <br /> &lt;%			            //e.printStackTrace(); <br /> 			            //throw new RuntimeException("FTP客戶端錯誤！", e); <br /> 					}<br /> 			     }<br /> 		    } catch (Exception e) {<br /> %&gt;				&lt;script language=javascript&gt;window.alert("FTP上傳失敗！&lt;%=e.getMessage()%&gt;！請重試！");&lt;/script&gt;<br /> &lt;%		    }<br /> 		}<br />     }		<br /> %&gt;[/code]]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/453.page</guid>
				<link>http://www.andowson.com/posts/preList/199/453.page</link>
				<pubDate><![CDATA[Wed, 3 Sep 2008 13:28:58]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ andowson 請教一下...<br /> 如果要上傳檔案之前,我想在FTP上判斷A目錄是否存在?<br /> 如果存在,就放入A目錄<br /> 不存在,就建立( [color=red]makeDirectory() [/color])A目錄....<br /> <br /> 判斷A目錄是否存在該怎麼做?]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/457.page</guid>
				<link>http://www.andowson.com/posts/preList/199/457.page</link>
				<pubDate><![CDATA[Thu, 4 Sep 2008 19:21:12]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 這個很簡單啊，用FTPClient類別的listFiles()來取得現行工作目錄的檔案清單(FTPFile[])，然後跑一個for迴圈，將每個元素拿出來判斷是否是一個目錄(isDirectory())且名稱(getName())等於目錄A，如果存在就終止迴圈，並將變數dirExist設定為true。<br /> [code]<br /> if (ftp.login(username, password)) {<br /> 	boolean dirExist = false;<br /> 	String dirA = &quot;upload&quot;;<br /> 	FTPFile[] files = ftp.listFiles();<br /> 	for (int i = 0; i &lt; files.length; i++) {<br /> 	         if (files[i].isDirectory() && files[i].getName().equals(dirA)) {<br /> 	            dirExist = true;<br /> 	            break;<br /> 	        }<br /> 	}<br /> 	out.println(&quot;directory &quot; + dirA + &quot; exists? &quot; + dirExist);<br /> 	if (!dirExist) {<br /> 	       ftp.makeDirectory(dirA);<br /> 	}<br /> }<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/458.page</guid>
				<link>http://www.andowson.com/posts/preList/199/458.page</link>
				<pubDate><![CDATA[Fri, 5 Sep 2008 01:15:20]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ 感謝指導....^^<br /> ]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/459.page</guid>
				<link>http://www.andowson.com/posts/preList/199/459.page</link>
				<pubDate><![CDATA[Fri, 5 Sep 2008 14:57:14]]> GMT</pubDate>
				<author><![CDATA[ viva]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ FTPS(FTP Secure or FTP over SSL/TLS)<br /> <br /> 預先安裝函式庫：[url=http://sourceforge.net/projects/ftp4che]ftp4che[/url], [url=http://logging.apache.org/log4j/1.2/download.html]log4j[/url]<br /> 程式碼：<br /> ftp4che.jsp: <br /> [code]<br /> &lt;%@ page import="java.io.File"%&gt;<br /> &lt;%@ page import="java.io.IOException"%&gt;<br /> &lt;%@ page import="org.ftp4che.*"%&gt;<br /> &lt;%@ page import="org.ftp4che.util.ftpfile.*"%&gt;<br /> &lt;%@ page import="org.ftp4che.exception.*"%&gt; <br /> &lt;%@ page import="org.ftp4che.impl.SecureFTPConnection"%&gt;<br /> &lt;%<br /> 	String server = "192.168.1.2";<br /> 	String username = "andowson";<br /> 	String password = "changeit";<br /> 	String directory = "download";<br /> 	String filename = "C:\\Users\\Andowson\\Desktop\\jspSmartUpload.zip";<br /> 	File filePut = new File(filename);<br /> 	String filename2 = "C:\\Users\\Andowson\\Desktop\\commons-net-1.4.1.zip";<br /> 	File fileGet = new File(filename2);<br /> 	String filename3 = "jdk-6u3-windows-i586-p.exe";<br /> 	<br /> 	FTPConnection ftp = null;<br /> 	try {<br /> 		ftp = FTPConnectionFactory.getInstance(server, 21, username, password, FTPConnection.AUTH_TLS_FTP_CONNECTION, true);<br />         ftp.connect();<br /> 		System.out.println("Connected to " + server + ".");<br /> 		<br /> 		// transfer files<br /> 		long totalSize = 0L;<br /> 		for (FTPFile file : ftp.getDirectoryListing(directory)) {<br /> 			System.out.printf("%s %s [%d bytes]\n",<br /> 					(file.isDirectory() ? "[D]" : "   "), file.getName(), file.getSize());<br /> 			if (!file.isDirectory()) {<br /> 				totalSize += file.getSize();<br /> 			} <br /> 		}			<br /> 		System.out.println("totalSize = " + totalSize/(1024 * 1024) + "MB");<br /> 		<br /> 		// PASV<br /> 		ftp.setPassiveMode(true);<br /> 		// CWD<br /> 		ftp.changeDirectory(directory);<br /> 		// PWD<br /> 		System.out.println(ftp.getWorkDirectory());		<br /> 		// PUT<br /> 		FTPFile fromFile = new FTPFile(filePut);<br /> 		FTPFile toFile = new FTPFile(new File(filePut.getName()));<br /> 		ftp.uploadFile(fromFile, toFile);<br /> 		// GET<br /> 		fromFile = new FTPFile(new File(fileGet.getName()));<br /> 		toFile = new FTPFile(fileGet);<br /> 		ftp.downloadFile(fromFile, toFile);<br /> 		// DELE<br /> 		ftp.deleteFile(new FTPFile(new File(filename3)));<br /> 	} catch (NotConnectedException nce) {<br /> 		nce.printStackTrace();<br /> 	} catch (FtpFileNotFoundException ffnfe) {<br /> 		ffnfe.printStackTrace();<br /> 	} catch (IOException e) {<br /> 		e.printStackTrace();<br /> 	} finally {<br /> 		if (ftp != null) {<br /> 			ftp.disconnect();<br /> 		}<br /> 	}<br /> %&gt;<br /> [/code]<br /> 備註：<br /> 最近找到了支援FTPS的免費Java FTP Library（採用LGPL授權） -- ftp4che，將原先的程式碼略微修改一下，搭配[url=http://filezilla-project.org/]FileZilla Server[/url]測試一下，可以成功執行。<br /> 參考資料：<br /> http://www.javaworld.com.tw/jute/post/view?bid=11&id=237813&sty=3]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/563.page</guid>
				<link>http://www.andowson.com/posts/preList/199/563.page</link>
				<pubDate><![CDATA[Wed, 25 Feb 2009 08:20:39]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
			<item>
				<title>回覆:JSP精選實用範例(四):檔案傳輸</title>
				<description><![CDATA[ SFTP(SSH File Transfer Protocol or FTP over SSH)<br /> <br /> 預先安裝函式庫：[url=http://www.jcraft.com/jsch/]JSch(Java Secure Channel)[/url]<br /> 程式碼：<br /> sftp.jsp:<br /> [code]<br /> &lt;%@ page import="java.io.File"%&gt;<br /> &lt;%@ page import="java.io.FileInputStream"%&gt;<br /> &lt;%@ page import="java.io.FileOutputStream"%&gt;<br /> &lt;%@ page import="java.util.Properties"%&gt;<br /> &lt;%@ page import="java.util.Vector"%&gt;<br /> &lt;%@ page import="com.jcraft.jsch.Channel"%&gt;<br /> &lt;%@ page import="com.jcraft.jsch.ChannelSftp"%&gt;<br /> &lt;%@ page import="com.jcraft.jsch.JSch"%&gt;<br /> &lt;%@ page import="com.jcraft.jsch.Session"%&gt;<br /> &lt;%@ page import="com.jcraft.jsch.ChannelSftp.LsEntry"%&gt;<br /> &lt;%<br /> 	try {<br /> 		String host = &quot;192.168.1.2&quot;;<br /> 		int port = 22;<br /> 		String username = &quot;andowson&quot;;<br /> 		String password = &quot;changeit&quot;;<br /> 		String directory = &quot;/home/andowson/download/&quot;;<br /> 		String uploadFile = &quot;C:\\temp\\upload.txt&quot;;<br /> 		<br /> 		String downloadFile = &quot;C:\\temp\\download.txt&quot;;<br /> 		String deleteFile = &quot;delete.txt&quot;;<br /> 	<br /> 		//<br /> 		// First Create a JSch session<br /> 		//<br /> 		System.out.println(&quot;Creating session.&quot;);<br /> 		JSch jsch = new JSch();<br /> 		ChannelSftp sftp = null;<br /> 	<br /> 		//<br /> 		// Now connect and SFTP to the SFTP Server<br /> 		//<br /> 		try {<br /> 			// Create a session sending through our username and password<br /> 			Session sshSession = jsch.getSession(username, host, port);<br /> 			System.out.println(&quot;Session created.&quot;);<br /> 			sshSession.setPassword(password);<br /> 			// Security.addProvider(new com.sun.crypto.provider.SunJCE());<br /> 	<br /> 			//<br /> 			// Setup Strict HostKeyChecking to no so we don't get the<br /> 			// unknown host key exception<br /> 			//<br /> 			Properties sshConfig = new Properties();<br /> 			sshConfig.put(&quot;StrictHostKeyChecking&quot;, &quot;no&quot;);<br /> 			sshSession.setConfig(sshConfig);<br /> 			sshSession.connect();<br /> 			System.out.println(&quot;Session connected.&quot;);<br /> 	<br /> 			//<br /> 			// Open the SFTP channel<br /> 			//<br /> 			System.out.println(&quot;Opening Channel.&quot;);<br /> 			Channel channel = sshSession.openChannel(&quot;sftp&quot;);<br /> 			channel.connect();<br /> 			sftp = (ChannelSftp) channel;<br /> 			System.out.println(&quot;Connected to &quot; + host + &quot;.&quot;);<br /> 		} catch (Exception e) {<br /> 			System.err.println(&quot;Unable to connect to FTP server.&quot; + e.toString());<br /> 			throw e;<br /> 		}<br /> 	<br /> 		//<br /> 		// Change to the remote directory<br /> 		//<br /> 		System.out.println(&quot;Changing to FTP remote dir: &quot; + directory);<br /> 		// CWD<br /> 		sftp.cd(directory);<br /> 		// PWD<br /> 		System.out.println(sftp.pwd());<br /> 	<br /> 		//<br /> 		// Send the file we generated, PUT<br /> 		//<br /> 		File filePut = new File(uploadFile);<br /> 		try {				<br /> 			System.out.println(&quot;Storing file as remote filename: &quot;	+ filePut.getName());<br /> 			sftp.put(new FileInputStream(filePut), filePut.getName());<br /> 		} catch (Exception e) {<br /> 			System.err.println(&quot;Storing remote file failed.&quot; + e.toString());<br /> 			throw e;<br /> 		}<br /> 	<br /> 		//<br /> 		// Get the list of files in the remote server directory<br /> 		//<br /> 		Vector files = sftp.ls(directory);<br /> 	<br /> 		//<br /> 		// Log if we have nothing to download<br /> 		//<br /> 		if (files.size() == 0) {<br /> 			System.out.println(&quot;No files are available for download.&quot;);<br /> 		}<br /> 		//<br /> 		// Otherwise download all files except for the . and .. entries<br /> 		//<br /> 		else {<br /> 			long totalSize = 0L;<br /> 			for (int i = 0; i &lt; files.size(); i++) {<br /> 				LsEntry file = (LsEntry) files.get(i);					<br /> 				if (!file.getFilename().equals(&quot;.&quot;)	&& !file.getFilename().equals(&quot;..&quot;)) {<br /> 					System.out.printf(&quot;%s %s [%d bytes]\n&quot;,<br /> 							(file.getAttrs().isDir() ? &quot;[D]&quot; : &quot;   &quot;), file.getFilename(), file.getAttrs().getSize());<br /> 					if (!file.getAttrs().isDir()) {<br /> 						totalSize += file.getAttrs().getSize();<br /> 					}						<br /> 				}<br /> 			}<br /> 			System.out.println(&quot;totalSize = &quot; + totalSize/(1024 * 1024) + &quot;MB&quot;);<br /> 			//<br /> 			// Get the file and write it to our local file system, GET<br /> 			//<br /> 			System.out.println(&quot;Downloading file &quot; + filePut.getName());<br /> 			File fileGet = new File(downloadFile);<br /> 			sftp.get(filePut.getName(), new FileOutputStream(fileGet));<br /> 			//<br /> 			// Remove the file from the server, DELE<br /> 			//<br /> 			System.out.println(&quot;Deleting file &quot; + deleteFile);<br /> 			sftp.rm(deleteFile);<br /> 		}<br /> 	<br /> 		//<br /> 		// Disconnect from the FTP server<br /> 		//<br /> 		try {<br /> 			sftp.quit();<br /> 		} catch (Exception e) {<br /> 			System.err.println(&quot;Unable to disconnect from FTP server. &quot;	+ e.toString());<br /> 		}<br /> 	<br /> 	} catch (Exception e) {<br /> 		System.err.println(&quot;Error: &quot; + e.toString());<br /> 		e.printStackTrace();<br /> 	}<br /> 	<br /> 	System.out.println(&quot;Process Complete.&quot;);<br /> %&gt;<br /> [/code]<br /> 參考資料：<br /> [url=http://timarcher.com/node/57]Sending Files via FTP From Your Java Applications - Part 2 of 2 - Using Jsch for SFTP[/url]]]></description>
				<guid isPermaLink="true">http://www.andowson.com/posts/preList/199/566.page</guid>
				<link>http://www.andowson.com/posts/preList/199/566.page</link>
				<pubDate><![CDATA[Thu, 26 Feb 2009 01:44:09]]> GMT</pubDate>
				<author><![CDATA[ andowson]]></author>
			</item>
	</channel>
</rss>
