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.
Related
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
We have a requirement to download video from google+/picasa and store it into sdcard.
Can you please any one help me to solve this issue?
google+/picasa
Converting from URI to byte[], then byte[] is stored to file:
InputStream videoStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(videoStream );
videoFile = new File("abcd.mp4");
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
Can you try that one :
public String DownloadFromUrl(String DownloadUrl, String fileName) {
File SDCardRoot = null;
try {
SDCardRoot = Environment.getExternalStorageDirectory();
File files = new File(SDCardRoot+fileName);
int sizeoffile;
if(!files.exists())
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath());
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl);
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
sizeoffile = ucon.getContentLength();
Log.d("SIZEOFFILE: ", sizeoffile+" BYTE");
/*
* 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(5000);
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.flush();
fos.close();
}
}
catch (IOException e) {
e.getMessage();
}
return SDCardRoot+fileName; }
Finally i found the solution.
Uri videoUri = data.getData();
File videoFile = null;
final InputStream imageStream;
try {
imageStream = getActivity().getContentResolver().openInputStream(videoUri);
byte bytes[] = ByteStreams.toByteArray(imageStream);//IStoByteArray(imageStream);
videoFile = new File(Environment.getExternalStorageDirectory()+ "/"+System.currentTimeMillis()+".mp4");
videoFile.createNewFile();
FileOutputStream out = new FileOutputStream(videoFile);
out.write(bytes);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}
I have recently encountered this.
I first discovered that what I'm receiving is a picture rather than a video.
But I didn't understand why Facebook is successfully playing the online video I shared via (Google+'s) Photo.
I then occasionally discovered that the file they're currently giving is a GIF with the original extension in the MediaStore.Images.Media.DISPLAY_NAME section of the contentUri.
Eeek!
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());
}
}
I having problem with file download,
I am able to download file in emulator but It is not working with the phone.
I have defined the permission for the Internet and write SD card.
I having one doc file on server, and if user click on download. It downloads the file. This works fine in emulator but not working in phone.
Edit
My code for download file
public void downloadFile(String _url, String fileName) {
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
PATH.mkdirs();
URL url = new URL(_url); // you can write here any link
File file = new File(PATH, fileName);
long startTime = System.currentTimeMillis();
Log.d("Manager", "download begining");
Log.d("DownloadManager", "download url:" + url);
Log.d("DownloadManager", "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);
}
}
try the snippets given bellow...
File PATH = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
_url = _url.replace(" ", "%20");
URL url = new URL(_url);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(PATH,fileName);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
Log.i("Download", totalSize+"");
//variable to store total downloaded bytes
// int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
}
//close the output stream when done
fileOutput.close();
return true;
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
make sure you have enters the correct download path(url)