2012-02-26 305 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