0

我正在尝试在我的 Android 应用程序中完成两件事:

  • 从服务器下载文件(pdf、图像和 html)
  • 下载文件后,保存服务器中的所有文件并显示在 Android 选项卡视图中

我的问题是,如何从服务器下载文件并将其显示在我的应用程序中?

我的下载代码如下所示:

public void downloadFiles () {

        try {

            URL url = new URL ("http://google.com/nexuspads.png");
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = Environment.getExternalStorageDirectory() + "/download/" ;

            Log.v ("LOG_TAG" , "PATH: " + PATH);
            File file = new File (PATH);
            file.mkdirs();

            String fileName = "image.png";

            File outputFile = new File (file, fileName);
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte [1024];

            int len1 = 0 ;

            while ((len1 = is.read(buffer)) != -1){

                fos.write (buffer, 0, len1);
            }

            fos .close();
            is.close();

        }catch (IOException e) {
            Log.d ("LOG_TAG2 ", "Error " + e );
//          Toast.makeText(,"error " +e.toString(), Toast.LENGTH_LONG).show();      
        }

    }
4

1 回答 1

0

要列出文件夹中的文件,可以按如下方式完成..

String path = Environment.getExternalStorageDirectory().toString()+"/YOUR folder here/";
            File f = new File(path);        
            final File listfile[] = f.listFiles();      
            String[] fileList = new String[listfile.length];
            for (int i=0; i < listfile.length; i++)     
            {
                fileList[i] =  listfile[i].getName();
                Log.v("Files", "FileName:" + listfile[i].getName());  
            }

然后您可以在警报对话框或 ListView 中显示结果。

于 2013-03-14T21:55:23.537 回答