由网友(酒香)分享简介:我使用下面的code,从我的服务器下载一个文件,然后把它写入SD卡的根目录下,这一切工作正常:包com.downloader;进口的java.io.File;进口java.io.FileOutputStream中;进口的java.io.InputStream;进口java.net.HttpURLConnectio...
我使用下面的code,从我的服务器下载一个文件,然后把它写入SD卡的根目录下,这一切工作正常:
包com.downloader;
进口的java.io.File;
进口java.io.FileOutputStream中;
进口的java.io.InputStream;
进口java.net.HttpURLConnection中;
进口的java.net.URL;
进口android.os.Environment;
进口android.util.Log;
公共类下载{
公共无效DownloadFile(字符串fileURL,字符串文件名){
尝试 {
文件根= Environment.getExternalStorageDirectory();
网址U =新的URL(fileURL);
HttpURLConnection的C =(HttpURLConnection类)u.openConnection();
c.setRequestMethod(GET);
c.setDoOutput(真正的);
c.connect();
FileOutputStream中F =新的FileOutputStream(新文件(根目录,文件名));
在的InputStream = c.getInputStream();
byte []的缓冲区=新的字节[1024];
INT LEN1 = 0;
而((LEN1 = in.read(缓冲液))大于0){
f.write(缓冲液,0,LEN1);
}
f.close();
}赶上(例外五){
Log.d(下载,e.getMessage());
}
}
}
然而,使用 Environment.getExternalStorageDirectory();
意味着该文件将永远写入根到/ mnt / SD卡
。是否可以指定一个特定的文件夹写入文件?
例如:到/ mnt / SD卡/ MyApp的/下载
干杯
EEF
解决方案 文件SD卡= Environment.getExternalStorageDirectory();
文件DIR =新的文件(sdCard.getAbsolutePath()+/ DIR1 / DIR2);
dir.mkdirs();
档案文件=新的文件(目录,文件名);
FileOutputStream中F =新的FileOutputStream(文件);
...
I am using the following code to download a file from my server then write it to the root directory of the sd card, it all works fine:
package com.downloader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Environment;
import android.util.Log;
public class Downloader {
public void DownloadFile(String fileURL, String fileName) {
try {
File root = Environment.getExternalStorageDirectory();
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
FileOutputStream f = new FileOutputStream(new File(root, fileName));
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
}
}
However, using Environment.getExternalStorageDirectory();
means that the file will always write to the root /mnt/sdcard
. Is it possible to specify a certain folder to write the file to?
For example: /mnt/sdcard/myapp/downloads
Cheers
Eef
解决方案File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
...
相关推荐
最新文章