0

你好,我使用了下面的代码,我在 android 应用程序的 android 3.0 平板电脑模拟器中运行项目,我得到路径 /mnt/sdcard/ 但没有得到完整路径。如何解决它?请帮助我!!下面是我的代码

![package com.hope.project;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    WebView myWebView;
    TextView mDisplay;
    AsyncTask<Void, Void, Void> mRegisterTask;
    String name;
    String Message;
    String deviceId;
    String regId;
    IntentFilter gcmFilter;
    SharedPreferences sharedPref;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myWebView = (WebView) findViewById(R.id.webView1);

        final JavaScriptInterface myJavaScriptInterface = new JavaScriptInterface(
                this);
        myWebView.addJavascriptInterface(myJavaScriptInterface,
                "AndroidFunction");

        WebSettings settings = myWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setBuiltInZoomControls(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadWithOverviewMode(true);
        myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

        myWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                // handle stuff here
                // e.g. view.loadUrl(url);
                Log.v("log", " on ovverRide " + url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                // dismiss the indeterminate progress dialog
                Log.v("log", "onPageFinished: " + url);
                myWebView.setEnabled(false);

            }
        });

        myWebView.loadUrl("file:///android_asset/www/index.html");
    /*  File urlName= Environment.getExternalStorageDirectory().getAbsoluteFile();
        Log.v("log_tag", "urlNameDownload "+urlName);*/

        /* File file\[\] = Environment.getExternalStorageDirectory().listFiles(); 
         for (File f : file)
            {
                if (f.isDirectory()) { 
                    String uri=f.getPath().substring(f.getPath().lastIndexOf("/") + 1);
                    Log.v("Name", uri);
                    Log.v("Name", f.getPath()+ "");
                    Log.v("Name", f.getAbsolutePath()+ "");

                }
            }*/

        File dir = new File("mnt/sdcard/");

        File\[\] files = (new File("mnt/sdcard/")).listFiles();

        // This filter only returns directories
        FileFilter dirFilter = new FileFilter() {
            public boolean accept(File dir) {
                return dir.isDirectory();
            }
        };

        files = dir.listFiles(dirFilter);

        for (int i=0; i<files.length; i++) {
            if(files\[i\].getAbsolutePath().contains("Download"))
              Log.v("log_tag","directory path : " + files\[i\].getAbsolutePath().substring(files\[i\].getAbsolutePath().lastIndexOf("/") +1));
        }
    }


    protected void onDestroy() {
        super.onDestroy();
    }

    public class JavaScriptInterface {
        Context mContext;

        JavaScriptInterface(Context c) {
            mContext = c;
        }

        public void DownloadUrl(String url) {
            Log.v("log", "login main url " + url);

            String file_url = url;

            new DownloadFileFromURL().execute(file_url);
            /*
             * String url_new = "http://"+url; Intent i = new
             * Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url_new));
             * startActivity(i);

*/
        }
    }

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            Log.v("log", "login main url\[0\] " + f_url\[0\]);
            try {
                URL url = new URL(f_url\[0\]);
                name = f_url\[0\].substring(f_url\[0\].lastIndexOf("/") + 1);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream to write file
                // OutputStream output = new
                // FileOutputStream("/sdcard/downloadedfile.jpg");
                OutputStream output = new FileOutputStream(
                        Environment.getExternalStorageDirectory() + "/Download/" + name);

                // OutputStream output = new
                // FileOutputStream("/sdcard/downloadedUrl.mp4");
                byte data\[\] = new byte\[1024\];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            // pDialog.setProgress(Integer.parseInt(progress\[0\]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            // dismissDialog(progress_bar_type);
            // Displaying downloaded image into image view
            // Reading image path from sdcard

            /*
             * Log.v("log","login main url\[0\] " +
             * Environment.getExternalStorageDirectory().toString()); String
             * videoPath = Environment.getExternalStorageDirectory() +"/"+name;
             * Intent i = new Intent(MainActivity.this,
             * VideoPlayActivity.class); i.putExtra("videoPath", videoPath);
             * startActivity(i);
             */

            Toast.makeText(MainActivity.this, "DownLoad Is Completed",
                    Toast.LENGTH_LONG).show();
        }

    }

}

我的 sdcard 屏幕截图如下:

4

1 回答 1

1

mnt/sdcard/您应该使用Environment对象,而不是硬编码。

具体来说:

File dir = Environment.getExternalStorageDirectory();

将为您提供一个文件对象,该对象自动指向运行它的设备的外部存储的正确位置。

此外,您已经发布了整个活动。其中绝大多数与您遇到的问题无关。将来,如果您取出与您遇到的问题特别相关的一小部分代码,您更有可能在 StackOverflow 上获得很好的帮助。它使正在回答的人更容易弄清楚您的情况。

于 2013-01-31T14:25:59.957 回答