如何将文件从网站保存到SD卡

RAA*_*AAM 11 android download sd-card

有谁知道如何通过wifi将文件从网络服务器(本地主机)保存到SD卡?

我正在对我的应用程序进行xml解析,为此我必须从localhost下载一个xml文件到sdcard,然后标记解析.我很难将xml文件下载到SD卡.请指导我如何做到这一点..

Sou*_*rav 42

您可以使用此方法将文件从Internet下载到SD卡:

public void DownloadFromUrl(String DownloadUrl, String fileName) {

   try {
           File root = android.os.Environment.getExternalStorageDirectory();               

           File dir = new File (root.getAbsolutePath() + "/xmls");
           if(dir.exists()==false) {
                dir.mkdirs();
           }

           URL url = new URL(DownloadUrl); //you can write here any link
           File file = new File(dir, fileName);

           long startTime = System.currentTimeMillis();
           Log.d("DownloadManager", "download begining");
           Log.d("DownloadManager", "download url:" + url);
           Log.d("DownloadManager", "downloaded file name:" + fileName);

           /* Open a connection to that URL. */
           URLConnection ucon = url.openConnection();

           /*
            * Define InputStreams to read from the URLConnection.
            */
           InputStream is = ucon.getInputStream();
           BufferedInputStream bis = new BufferedInputStream(is);

           /*
            * Read bytes to the Buffer until there is nothing more to read(-1).
            */
           ByteArrayBuffer baf = new ByteArrayBuffer(5000);
           int current = 0;
           while ((current = bis.read()) != -1) {
              baf.append((byte) current);
           }


           /* Convert the Bytes read to a String. */
           FileOutputStream fos = new FileOutputStream(file);
           fos.write(baf.toByteArray());
           fos.flush();
           fos.close();
           Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

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

}
Run Code Online (Sandbox Code Playgroud)

您需要将以下权限添加到AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Run Code Online (Sandbox Code Playgroud)

  • 我不喜欢逐字节读取只需将其更改为某个缓冲版本,接下来为什么在将wana写入文件(另一个流)时将整个流读取到ByteArrayBuffer ...所以更好的解决方案是`int count; byte [] buffer = new byte [8192]; while((count = in.read(buffer))> 0)out.write(buffer,0,count);` (4认同)
  • -1对于'while((current = bis.read())!= -1)`代码段说"NO" (3认同)