Android-从服务器上的文件夹下载所有文件
希望我能正确解释这一点。。。 我可以连接到我的web服务器并下载单个文件。我现在尝试的是连接到我的服务器并从特定文件夹下载所有苍蝇。在这种情况下,我要下载图像。 这是我用来下载单个文件的代码Android-从服务器上的文件夹下载所有文件,android,Android,希望我能正确解释这一点。。。 我可以连接到我的web服务器并下载单个文件。我现在尝试的是连接到我的服务器并从特定文件夹下载所有苍蝇。在这种情况下,我要下载图像。 这是我用来下载单个文件的代码 URL url = new URL("http://127.0.0.1/Folder/file.csv"); URLConnection conexion = url.openConnection(); conexion.connect();
URL url = new URL("http://127.0.0.1/Folder/file.csv");
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory =
new File(Environment.getExternalStorageDirectory()+"/Folder");
if(!testDirectory.exists()){
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory+"/file.csv");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count=is.read(data)) != -1){
total += count;
int progress_temp = (int)total*100/lenghtOfFile;
if(progress_temp%10 == 0 && progress != progress_temp){
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
如何添加到该代码中,使其从该文件夹下载所有文件?我建议您在服务器端使用一个脚本,它首先为您提供文件夹中所有文件的列表,然后您的应用程序逐个下载每个文件。
公共类下载文件服务扩展服务实现ConfigCommonVars{
public class DownloadFileService extends Service implements ConfigCommonVars {
private static final int NOTIFICATION = 0;
private NotificationManager mNM;
File SDCardRoot = Environment.getExternalStorageDirectory();
ArrayList<String> mServerFileListApp = new ArrayList<String>();
ArrayList<String> mDeviceFileListApp = new ArrayList<String>();
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
Toast.makeText(this, " device Services ",Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
File directory = new File(SDCardRoot+DOC_FOLDER_NAME);
// create directory if not exists
if(!directory.exists())
{
if(directory.mkdirs()) //directory is created;
Log.i(" download ","App dir created");
else
Log.w(" download ","Unable to create app dir!");
}
mDeviceFileListApp = getDeviceFiles();
Toast.makeText(this, " device file "+mDeviceFileListApp.toString(),Toast.LENGTH_LONG).show();
new Thread(new Runnable() {
public void run() {
try {
mServerFileListApp = getServerFiles();
}catch(Exception e)
{
e.printStackTrace();
}
}
}).start();
return START_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(NOTIFICATION);
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
private void showNotification() {
/*// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, this.Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label),text, contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
*/
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public ArrayList<String> getDeviceFiles()
{
mDeviceFileListApp = new ArrayList<String>();
File directory = new File(SDCardRoot+DOC_FOLDER_NAME);
if(directory.length()!=0) // check no of files
{
for (File file : directory.listFiles()) {
if (file.isFile())
mDeviceFileListApp.add(file.getName());
}
}
return mDeviceFileListApp;
}
public ArrayList<String> getServerFiles()
{
InputStream inputStream = null;
JSONArray mFileArray = null;
String mfileNames ;
mServerFileListApp = new ArrayList<String>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(HTTP+SITE_URL+WEB_SERVICES_PATH+"bmservicecontroller.php?PAGE=loginpage&OPTION=downloadFile&TYPE=1");
// get list of file in download folder
try
{
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader= new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder builder= new StringBuilder();
char[] buf = new char[1000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = reader.read(buf);
}
inputStream.close();
JSONTokener tokener = new JSONTokener( builder.toString());
JSONObject finalResult = new JSONObject( tokener );
mFileArray = finalResult.getJSONObject("FSSEAPI").getJSONArray("FileName");
for (int i = 0; i < mFileArray.length(); i++)
{
try {
mfileNames = mFileArray.getString(i);
mServerFileListApp.add(mfileNames);
} catch (Exception e) {
//showError("File Not Found " + mfileNames);
e.printStackTrace();
}
} // for ends
String temp;
for (int i=0; i<mServerFileListApp.size(); i++)
{
temp = mServerFileListApp.get(i);
if(! mDeviceFileListApp.contains(temp))
{
Log.i(" File Download Start ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
downloadFileManager(HTTP+SITE_URL+DOWNLOAD_PATH,temp);
}
else
{
// check and Delete File Exists
Log.i(" File Deleted ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
/*
File checkFile = new File(SDCardRoot+DOC_FOLDER_NAME+temp);
if(checkFile.exists())
if(checkFile.delete())
Log.i(" File Deleted ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
else
Log.i(" File Not Delete ",HTTP+SITE_URL+DOWNLOAD_PATH+temp);
*/
}
}
}
catch(IOException e)
{
e.printStackTrace();
//showError("File Download Error ");
}
catch (JSONException e)
{
e.printStackTrace();
//showError("File Download Error ");
}
return mServerFileListApp;
}
public void downloadFileManager(String path,String file)
{
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(path+file));
request.setDescription(file+"descrition");
request.setTitle(file+"title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(DOC_FOLDER_NAME, file);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
}
私有静态最终整数通知=0;
私人通知经理mNM;
文件SDCardRoot=Environment.getExternalStorageDirectory();
ArrayList mServerFileListApp=新建ArrayList();
ArrayList mDeviceFileListApp=新建ArrayList();
@凌驾
public void onCreate(){
mNM=(NotificationManager)getSystemService(通知服务);
//显示关于我们开始的通知。我们在状态栏中放置了一个图标。
showNotification();
Toast.makeText(这是“设备服务”,Toast.LENGTH_LONG).show();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.i(“本地服务”,“收到的启动id”+startId+:“+intent”);
//我们希望此服务继续运行,直到显式恢复
//停止,所以返回粘性。
文件目录=新文件(SDCardRoot+文档文件夹名称);
//如果不存在,则创建目录
如果(!directory.exists())
{
如果创建了(directory.mkdirs())//目录;
Log.i(“下载”、“创建应用程序目录”);
其他的
Log.w(“下载”,“无法创建应用程序目录!”);
}
mDeviceFileListApp=getDeviceFiles();
Toast.makeText(这个“设备文件”+mDeviceFileListApp.toString(),Toast.LENGTH_LONG.show();
新线程(newrunnable()){
public void run(){
试一试{
mServerFileListApp=getServerFiles();
}捕获(例外e)
{
e、 printStackTrace();
}
}
}).start();
返回开始时间;
}
@凌驾
公共空间{
//取消持久通知。
mNM.取消(通知);
//告诉用户我们停止了。
Toast.makeText(this,R.string.local_服务已停止,Toast.LENGTH_SHORT.show();
}
私有void showNotification(){
/*//在这个示例中,我们将对股票代码和扩展通知使用相同的文本
CharSequence text=getText(R.string.local\u服务\u已启动);
//设置图标、滚动文本和时间戳
通知通知=新通知(R.drawable.stat_示例,文本,System.currentTimeMillis());
//如果用户选择此通知,则PendingEvent将启动我们的活动
PendingEvent contentIntent=PendingEvent.getActivity(this,0,新意图(this,this.Controller.class),0);
//设置通知面板中显示的视图的信息。
setLatestEventInfo(this,getText(R.string.local\u service\u label),text,contentIntent);
//发送通知。
通知(通知,通知);
*/
}
@凌驾
公共IBinder onBind(意图arg0){
//TODO自动生成的方法存根
返回null;
}
公共阵列列表getDeviceFiles()
{
mDeviceFileListApp=新的ArrayList();
文件目录=新文件(SDCardRoot+文档文件夹名称);
if(directory.length()!=0)//检查文件的数量
{
对于(文件:directory.listFiles()){
if(file.isFile())
mDeviceFileListApp.add(file.getName());
}
}
返回mDeviceFileListApp;
}
公共ArrayList getServerFiles()
{
InputStream InputStream=null;
JSONArray mFileArray=null;
字符串名称;
mServerFileListApp=newArrayList();
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost-HttpPost=newhttppost(HTTP+SITE\u URL+WEB\u SERVICES\u PATH+“bmservicecontroller.php?PAGE=loginpage&OPTION=downloadFile&TYPE=1”);
//获取下载文件夹中的文件列表
尝试
{
HttpResponse response=httpclient.execute(httppost);
HttpEntity HttpEntity=response.getEntity();
inputStream=httpEntity.getContent();
BufferedReader=新的BufferedReader(新的InputStreamReader(inputStream,“UTF-8”));
StringBuilder=新的StringBuilder();
char[]buf=新字符[1000];
int l=0;
而(l>=0)
{
附加(buf,0,l);
l=读卡器读取(buf);
}
inputStream.close();
JSONTokener tokener=新的JSONTokener(builder.toString());
JSONObject finalResult=新的JSONObject(标记器);
mFileArray=finalResult.getJSONObject(“FSSEAPI”).getJSONArray(“文件名”);
对于(int i=0;i
hmmm这是唯一的方法吗?如果是的话,你知道我可以去哪里找到这样的脚本吗?而且文件夹将有不同类型的图像,具有唯一的图像名称,脚本是否能够保持