方法一:

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) {
e.printStackTrace();
Log.d("DownloadManager", "Error: " + e);
}

}


方法二:

protected void download() {
File root = Environment.getExternalStorageDirectory();
File file = new File(root, "myPDF" + ".pdf");
String content = null;
try {
if (root.canWrite()) {

String[] paramterNames = new String[1];
String[] paramterValues = new String[1];
paramterNames[0] = "respFormat";
paramterValues[0] = "pdf";
URL url = new URL(uri);

try {

// Read the PDF from the URL and save to
// a local file
BufferedInputStream bis = new BufferedInputStream(
url.openStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
byte[] buff = new byte[2048];
int bytesRead;
// Simple read/write loop.
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bos.flush();
bos.close();
bis.close();

} catch (NullPointerException npe) {
System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");
}

}
} catch (IOException e) {
e.printStackTrace();
}
}


更多相关文章

  1. Android中 Bitmap和Drawable相互转换的方法
  2. Android 处理 Button 单击事件的三种方法
  3. [Android Studio导入第三方类库方法] Error:(19, 23) 错误: 程序
  4. Android 中数据库查询方法query()中的selectionArgs的用法
  5. android客户端向服务器端验证登陆方法的实现2
  6. Unity-Android通信:AndroidJava 使用Unity c#编写Android程序调用
  7. Android例子—设置Activity全屏的三种方法
  8. Android stuio在MainActivity中运行java的main方法
  9. android中的提示信息显示方法(toast应用)

随机推荐

  1. phonegap2.5在android开发平台的环境搭建
  2. Android(安卓)查看及设置 SELinux 状态
  3. Android简单登陆页面
  4. Android开发常用功能整理
  5. Android第三方文件选择器aFileChooser使
  6. 解决android:layout_marginBottom在Relat
  7. Android:Installation error: INSTALL_FAI
  8. Android(安卓)对集合对象排序(快排与实现
  9. Android(安卓)高仿iReader标签
  10. android 反编译 整理