2012-10-04 71 views
0

我試圖從服務器下載幾個文本文件。它們都具有相似的名稱(例如text1.txt,txt2.txt),但具有不同的編號(每月更改數量)。我似乎無法下載這些文件。 Java一直告訴我它遇到了一個沒有找到文件的錯誤/異常。有誰知道我怎麼能通過這個?從服務器下載多個文本文件,但是,找不到文件

下載類。

public class downloadText extends AsyncTask<String, String, String> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      showDialog(DIALOG_DOWNLOAD_PROGRESS); 
     } 

     @Override 
     protected String doInBackground(String... params) { 

      try { 


       File sourceLocation = new File(targetPath); 
       sources = sourceLocation.listFiles(); 

       Arrays.sort(sources); 


       File root = android.os.Environment 
         .getExternalStorageDirectory(); 
       File dir = new File(root.getAbsolutePath() + "aiyo/edition/text/"); 

       if (dir.exists() == false) { 
        dir.mkdirs(); 
       } 

       Log.d("param", params[0]); 
       URL url = new URL("http://create.aiyomag.com/assets/app_mag/ALYO/9_1342080926/text"); // you can write here any link 
       URLConnection connection = url.openConnection(); 
       connection.connect(); 

       int contentLength=connection.getContentLength(); 


       // get file name and file extension 


       String fileExtenstion = MimeTypeMap 
         .getFileExtensionFromUrl(params[0]); 
       String name = URLUtil.guessFileName(params[0], null, 
         fileExtenstion); 
       File file = new File(dir, name); 
       Log.d("File in content","The file is "+file.getName()); 

       /* 
       * Define InputStreams to read from the URLConnection. 
       */ 
       InputStream is = connection.getInputStream(); 
       BufferedInputStream bis = new BufferedInputStream(is); 
       OutputStream fos = new FileOutputStream(file); 

       /* 
       * Read bytes to the Buffer until there is nothing more to 
       * read(-1). 
       */ 

       int lenghtOfFile = connection.getContentLength(); 
       int total = 0; 
       byte baf[] = new byte[1024]; 
       int current = 0; 
       while ((current = bis.read(baf)) != -1) { 

        total += current; 
        // publishProgress("" + (int) ((total * 100)/
        // lenghtOfFile)); 
        mProgressDialog.setProgress(((total * 100)/lenghtOfFile)); 
        fos.write(baf, 0, current); 
       } 

       // close every file stream 
       fos.flush(); 
       fos.close(); 
       is.close(); 

      } catch (IOException e) { 
       Log.e("DownloadManager", "Error: " + e); 
      } 
      return null; 
     } 

     @Override 
     protected void onProgressUpdate(String... values) { 
      mProgressDialog.setProgress(Integer.parseInt(values[0])); 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      // TODO Auto-generated method stub 
      // if (fileInteger == max) { 
      //  dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
      //  return; 
      // } 


      Log.d("post execute", "i::" + fileInteger); 
      // fileInteger++; 
      // publishProgress("" + (int) ((fileInteger * 100)/max)); 
     // mProgressDialog.setSecondaryProgress(((fileInteger * 100)/max)); 
      String link = txturl; 

      downloadText = new downloadText(); 
      downloadText.execute(link); 
     } 

爲主。

btn_txt = (Button) findViewById(R.id.text); 

    btn_txt.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 

      String link; 
      link = txturl+fileInteger+".txt"; 

      new Thread(new Runnable() { 
       public void run() { 
        max = (totalFile(pageNum) - 1); 
        text.post(new Runnable() { 
         public void run() { 
          text.setText("" + max); 
         } 
        }); 
       } 
      }).start(); 

      downloadText = new downloadText(); 
      downloadText.execute(link);   
     } 

     }); 
+0

好吧,我得到一個403錯誤當我訪問那個鏈接... – Eric

+0

你是什麼意思? – akemalFirdaus

回答

1

當我訪問該鏈接時,出現403錯誤。這意味着可以訪問該頁面,但服務器禁止我訪問它。這就是爲什麼沒有文件正在下載,因此資源未找到錯誤。

如果您自己運行服務器,那麼您可以查看後端代碼和服務器配置,以瞭解發生這種情況的原因。否則,您需要聯繫服務器的管理員並請求訪問該頁面的權限。

一旦你獲得了必要的許可,您可以通過

  1. 通過URL的數組您doInBackground方法(每個文件)或

  2. 更好的下載文件的列表選項將要求管理員創建一個腳本來壓縮服務器上的文件並將其保存在指定的URL中。然後,您可以下載zip文件並將其解壓縮到您的應用中。這比逐個下載文件要好得多,因爲它節省了請求的數量,帶寬和錯誤可能性的數量。

示例代碼來壓縮在PHP文件:

<?php 

// Adding files to a .zip file, no zip file exists it creates a new ZIP file 

// increase script timeout value 
ini_set('max_execution_time', 5000); 

// create object 
$zip = new ZipArchive(); 

// open archive 
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) { 
    die ("Could not open archive"); 
} 

// initialize an iterator 
// pass it the directory to be processed 
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("themes/")); 

// iterate over the directory 
// add each file found to the archive 
foreach ($iterator as $key=>$value) { 
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key"); 
} 

// close and save archive 
$zip->close(); 
echo "Archive created successfully."; 
?> 

下載zip文件教程: http://www.java-samples.com/showtutorial.php?tutorialid=1521

解壓文件教程: http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29

+0

我已經問過她,她說我只能訪問這些文件,如果我知道這個名字。 txt文件的名稱是1,txt,2.txt,3.txt等。 它應該是這樣的http://create.aiyomag.com/assets/app_mag/ALYO/9_1342080926/text/1.txt 如何在不知道文件的確切範圍的情況下下載這些文件? – akemalFirdaus

+0

除非服務器啓用某種目錄索引,否則不能。如果你知道它們是按順序的(從1開始到X),你可以繼續下去。一旦你點擊X + 1,你會得到403(或404),你就可以停下來。我建議看一些關於一般HTTP傳輸的教程。 – irbull

+0

irbull我剛剛過去了解如何知道文件的範圍。現在我需要知道如何下載整個列表。有任何想法嗎? – akemalFirdaus