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);         
        }

        });
4

1 回答 1

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

于 2012-10-04T03:39:10.620 回答