2012-02-26 306 views
0

我正在寫一個小的android應用程序,它需要一些存儲在我的web服務器上的數據。該文件是一個.txt文件,小於1 MB。建議使用ftp服務器來獲取數據,或者我可以使用http get方法獲取文件中的內容。如果我正在使用http獲取某人請告訴我此操作所需的java代碼。從ftp服務器下載文件

回答

1

這是我的頭了(這樣的錯誤可能偷偷中):

URL url = new URL("http://www.yourserver.com/some/path"); 
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

try { 
    InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
    FileOutputStream out = new FileutputStream("/path/to/your/output/file"); 
    byte[] buffer = new byte[16384]; 
    int len; 
    while((len = in.read(buffer)) != -1){ 
     out.write(buffer, 0, len); 
    } 
finally { 
    urlConnection.disconnect(); 
} 
+0

爲避免你的應用程序標記爲「沒有響應」,確保做下載一個單獨的線程。請參閱AsyncTask上的Android頁面,http://developer.android.com/reference/android/os/AsyncTask.html。 – 2012-02-26 07:57:22

+0

是的,這是可行的。謝謝。 – user1092042 2012-02-26 08:03:34