Java 如何在android上下载文件并保存在SD卡中?
我想用async类下载文件,但当我想查找文件路径时出错了?这是android 6中的一个错误? java.io.FileNotFoundException:/sdcard/downloadedfile.jpg:open failed:enoint(没有这样的文件或目录)Java 如何在android上下载文件并保存在SD卡中?,java,android,Java,Android,我想用async类下载文件,但当我想查找文件路径时出错了?这是android 6中的一个错误? java.io.FileNotFoundException:/sdcard/downloadedfile.jpg:open failed:enoint(没有这样的文件或目录) 我添加了这些权限,但不起作用 您首先必须检查目录是否存在。如果它不存在,则必须首先创建目录 try { URL url = new URL(file_url);
我添加了这些权限,但不起作用 您首先必须检查目录是否存在。如果它不存在,则必须首先创建目录
try {
URL url = new URL(file_url);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download";
File file = new File(PATH);
if(!file.exists()) {
file.mkdirs();
}
String name=String.valueOf(code)+".mp4";
File outputFile = new File(file,name);
FileOutputStream fos =
new FileOutputStream(outputFile);//this line
InputStream is = c.getInputStream();
int fileLength = sizeoffile;
byte[] buffer = new byte[4096];
int len1 = 0;
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
if (fileLength > 0)
publishProgress((int) (total));
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
您的应用程序是否具有所需的权限?你以前做过一些研究吗?做一些研究你可以找到更多你想要的资源或查看此链接
File dir = new File("path/to/your/directory");
try{
if(dir.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory is not created");
}
}catch(Exception e){
e.printStackTrace();
}