我创建了一个Android应用程序来下载图像并将其保存到外部目录,但应用程序下载文件并将其保存到内部目录。 这是我的代码
protected String doInBackground(String... aurl) {
int count;
try {
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/storage/extSdCard/prateek");
if(dir.exists() == false){
dir.mkdirs();
}
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
// File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, to save the downloaded file
File file = new File(dir,"downloaded_file.png");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
答案 0 :(得分:0)
使用此 -
String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File dir = new File(exStoragePath + "/prateek/");
还在您的清单中加入<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
。
答案 1 :(得分:0)
这是一些创建文件并在其中编写“Hello world”的代码。该文件将存储在/ myDir目录中。
你应该添加
&LT; uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”/&gt;
到你的清单上工作。
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/myDir");
myDir.mkdirs();
File outFile = new File (myDir, "myFile");
FileWriter fileWriter = new FileWriter(outFile);
BufferedWriter out = new BufferedWriter(fileWriter);
out.write("Hello world");
out.close();
Toast.makeText(this, "File successfully created to "+outFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d("debug", "IOException: " + e.getMessage());
Toast.makeText(this, "Error: file NOT created", Toast.LENGTH_SHORT).show();
}
玩得开心。
答案 2 :(得分:0)
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/storage/extSdCard/prateek");
如果我是对的,你的上述代码会给你路径为&#34; mnt / sdcard / storage / extSdCard / prateek&#34;所以不要使用root.getAbsolutePath()直接给出路径&#34; / storage / extSdCard / prateek&#34;和 它也不是存储在外部卡中的好习惯,因为在kitkat版本和其他一些手机中它不提供外部卡它会假设内存作为extsdcard