我寫這段代碼用於下載我的android應用程序中的一些文件,但現在下載的文件在根目錄下沒有任何特殊的順序,它看起來非常糟糕!所以我想知道如何爲我的應用程序的下載文件添加一個文件夾?如何爲我的應用程序創建數據文件夾?
碼字行解釋輸出的路徑:
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + downloadedfileName);
這裏是我的代碼:
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
private String downloadedfileName;
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "بارگذاری...", Toast.LENGTH_SHORT).show();
pDialog = new ProgressDialog(DownloadActivity.this);
pDialog.setMessage("کتاب در حال بارگذاري، لطفا منتظر بمانيد...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(DownloadActivity.this)
.setTitle("دانلود کتاب با موفقیت انجام شد")
.setMessage("از دانلود شما سپاسگذاریم.")
.setNeutralButton("خواهش میکنم", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(DownloadActivity.this, LibActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
DownloadActivity.this.startActivity(i);
DownloadActivity.this.finish();
}
});
builder.create().show();
}
public void setDownloadedFileName(String downloadedfileName){
this.downloadedfileName = downloadedfileName;
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... surl) {
int count;
try {
URL url = new URL(surl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
//OutputStream output = new FileOutputStream(Environment
// .getExternalStorageDirectory().toString()
// + "/data/" + downloadedfileName);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/ketabha/" + downloadedfileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
}
可能重複[無法在Android設備上的外部存儲中創建文件夾](http://stackoverflow.com/questions/8387252/cant-create-a-folder-in-external-storage-on-android-device ) – mvillar 2014-11-24 13:58:02
@mvillar沒有親愛的我在我的清單中有這樣的權限。坦克你 – 2014-11-24 14:01:43