i have created an android application to download an image and save it to external directory but the application downloads the file and saves it to internal directory.
this is my code
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;
}
use this -
String exStoragePath = Environment.getExternalStorageDirectory().getAbsolutePath();
File dir = new File(exStoragePath + "/prateek/");
Also include <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to your manifest.
Here is some code to create a file and write "Hello world" in it. This file will be stored in /myDir directory.
You should add
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to your manifest for this to work.
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();
}
Have fun.
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/storage/extSdCard/prateek");
If I am right the above code of yours will give you path as "mnt/sdcard/storage/extSdCard/prateek" so instead of using root.getAbsolutePath() directly give the path "/storage/extSdCard/prateek" and
Its also not a good practice to store in external card since in kitkat version and some other phones it will not provide external card it will assume internal memory as extsdcard
Related
Android- Saving File (Input & Output Stream) throws Exception (open failed: EINVAL (Invalid argument)) in Pre-lollipop devices
I am downloading a file from URL (www.xyz.in/file/9) and saving in SD CARD.
Folder created code:
try {
//String folder_name = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), "Venky");
if (!f.exists()) {
f.mkdirs();
}
} catch (Exception e) {
Log.v("MTV", " createFileDirectory exception" + e);
}
Below I posted a (Download and Saving file) code,
In android lollipop, It works fine to download and saved the file in SD Card.
it doesn't works on Pre-lolipop devices. It throws Exception.
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
String depo = conection.getHeaderField("Content-Disposition");
String depoSplit[] = depo.split("filename=");
filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
filename=filename.trim();
String Filetype = conection.getContentType();
Log.v("fileName", " " + filename + " FileLength " + lenghtOfFile + " Filetype " + Filetype);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/Venky/" + filename);
Log.v("", "" + Environment.getExternalStorageDirectory().toString() + "/" + R.string.app_name + "/" + filename);
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();
DownloadSucess = true;
} catch (Exception e) {
DownloadSucess = false;
Log.e("Error: ","Download Exception "+ e);
}
return null;
}
Logcat (Exception):
>E/Error:: Download Exception java.io.FileNotFoundException: /storage/sdcard0/Venky/FileName : smile-please.png: open failed: EINVAL (Invalid argument)
Note: In manifest, Both WRITE_EXTERNAL_STORAGE & READ_EXTERNAL_STORAGE permissions are used.
The value of your variable filename is FileName : smile-please.png and not -what you think- smile-please.png.
Just log the contents of filename before use.
I guess you should first try to create that directory, the file and then check whether them exists or not.
String path = Environment.getExternalStorageDirectory().toString() + "/Venky/";
File dir = new File(path);
boolean created = dir.mkdir();
if (created) {
File fp = new File(path + filename);}
I am going with the download of files from the browser and stored in the internal storage of my device and the path appears as like /data/data/com.example/files/downloads/sample.pdf
but on next day i get the file path as empty ""
using below code to save the file from browser:
private String downloadfile(Uri uri) {
int count;
String fileName = "";
try {
// Output stream to write file
String root = null;
// if (Environment.isExternalStorageRemovable())
// else
root = getFilesDir().toString()+ "/download/";
File file = new File(root);
if (!file.exists())
file.mkdirs();
fileName = file.getAbsolutePath();
file = new File("" + uri);
fileName = fileName + "/" + file.getName();
URL url = new URL(uri.toString());
URLConnection conection = url.openConnection();
conection.setRequestProperty("Content-Type",
"application/octet-stream");
conection.setRequestProperty("Expect", "100-continue");
conection.setRequestProperty("Content-Disposition", "attachment");
conection.setRequestProperty("filename", file.getName());
conection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(fileName);
file = new File(fileName);
file.createNewFile();
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
String inputs = "EX";
Parameter.trackApplication(inputs, e.getMessage());
e.printStackTrace();
}
return fileName;
}
How can i solve this problem,please correct me where i am going wrong and help me out to fix this issue.
I'm trying to write some code to stream a file from a server directly into the Android external storage system.
private void streamPDFFileToStorage() {
try {
String downloadURL = pdfInfo.getFileServerURL();
URL url = new URL(downloadURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream pdfFileInputStream = new BufferedInputStream(httpURLConnection.getInputStream());
File pdfFile = preparePDFFilePath();
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
byte[] buffer = new byte[8012];
int bytesRead;
while ((bytesRead = pdfFileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private File preparePDFFilePath() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
return file;
/*
String pdfFileDirectoryPath = ApplicationDefaults.sharedInstance().getFileStorageLocation() + pdfInfo.getCategoryID();
File pdfFileDirectory = new File(pdfFileDirectoryPath);
pdfFileDirectory.mkdirs();
return pdfFileDirectoryPath + "/ikevin" + ".pdf";
*/
}
It keeps getting an exception of "No such file or directory" at
"OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));"
How do I write the file? What's wrong with my code? (Also, I am not using Context.getExternalFilesDir() because I don't know how to get the Context from my controller logic code. Can anyone advise if this is the better solution?)
new File is returning you a file object and not the file. You might wana create a file before opening a stream to it. Try this
File pdfFile = preparePDFFilePath();
boolean isCreated = pdfFile.createNewFile();
if(isCreated){
OutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));
}
This code works:
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File(root + "/dir1");
dir.mkdirs();
guys i have a text file in my URL.On click of a button i am able to download it to sdcard.
But i need to replace the downloaded file with the file in raw folder.Both are different files.
this is how i am downloading from URL
File sdcard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/varun");
dir.mkdirs();
try {
u = new URL("http://hihowru.com/123.xml");
file = new File(dir,"123.xml");
startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "downloaded file name:" + "a.mp3");
URLConnection uconnection = u.openConnection();
InputStream is = uconnection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos;
fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Toast toast = Toast.makeText(getApplicationContext(), "Downloaded to Sdcard/varun"+audioxml, 0);
toast.show();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
Intent ii = new Intent(DownloadFiles.this,Relaxation.class);
startActivity(ii);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but i need to replace this file(downloaded file) with the file in raw folder
download file name : hi.txt
raw folder name : hw.txt
how to acheive this please help
You can't modify or write a file in android resources or asset directory. Because of android apk file is read only. So you are able to only read it. Best way is copy that file in internal storage then use from that path, also after download file from url update that at internal storage path.
Update:
Code for copy file from /asset to application internal storage.
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
How Do I Copy songs or image to my SD Card. i.e download image and save to sd card in android.
Thanks , shiv
Try this code:
File src = new File(Your_current_file);
File dest = new File(destination_place);
public void copyFile(File src, File dest) throws IOException
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
}
Make sure to Give the permission for External Storage if you need:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Hope this will helps you.
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);
Dont forget to add permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
private final String PATH = "/data/data/com.whatever.whatever/"; //put the downloaded file here
public void DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
try {
URL url = new URL("http://yoursite.com/" + imageURL); //you can write here any link
File file = new File(fileName);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "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(50);
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.close();
Log.d("ImageManager", "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
}
And don't forget to add the following permissions:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = new File(path, "DemoPicture.jpg");
try {
// Make sure the Pictures directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = //Input stream of the file downloaded;
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}