i follow more explain in this site for download mp3 or picture from URL , I follow more method and try to write my method but when i run application it stop.
I make method to query download when click
also put permission for INTERNET & WRITE_EXTERNAL_STORAGE
put the problem is still
this method is download
public static void downloadMain(){
File fileToSave = null;
String scrPath ="http://***";
BufferedInputStream bis;
BufferedOutputStream bos;
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
fileToSave = new File(Environment.getExternalStorageDirectory().getPath() +"/"+ "A" +"/" + "h"+"/");
if (!fileToSave.exists())
fileToSave.mkdirs();
File file = new File (fileToSave,"***.mp3");
try{
URL url = new URL(scrPath+"***.mp3");
URLConnection ucon = url.openConnection();
ucon.connect();
bis=new BufferedInputStream(ucon.getInputStream());
bos = new BufferedOutputStream(new FileOutputStream(file));
bis=new BufferedInputStream(url.openStream());
byte[] data = new byte[1024];
int a =0;
while(true){
int k = bis.read(data);
if(k==-1){
bis.close();
bos.flush();
bos.close();
break;
}
bos.write(data, 0, k);
a+=k;
}
}catch(IOException e){}
}
I have three main perplexity about your program:
Do you run the following code in an asynctask? (this must run asincronusly otherwise it will block)
Why it loop infinitly?
You couldn't open an url or a file named with a '*' inside of it
Edit:
You must run the download method asincronusly otherwise it wouldn't work, interaction with filesystem and network couldn't be done in the main thread
Edit2:
AsyncTask should be something like this
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");//put here your path and your mkdirs
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
}
And you shoould call it like this
DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
You could also have a look at this answer
Related
I tried using many codes I've found for downloading files with an AsyncTask with no success yet.
I get an error on the logcat: E/Error:: No such file or directory.
Despite looking for solutions for this error, couldn't find What's missing or wrong.
This is the doInBackground method in which I assume something is missing/wrong:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}
protected String doInBackground(String...fileUrl) {
int count;
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(fileUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File fileName = new File(root+"/movies.json");
boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing
// Output stream to write file
OutputStream output = new FileOutputStream(fileName,false);
byte data[] = new byte[1024];
System.out.println("Downloading");
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// 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;
}
Thanks.
Didn't want to bombard with redundant code. If some other code is needed, I'd love to provide it.
UPDATED ANSWER
this is working for me, write file in local storage and read it again on method PostExecute
class DownloadJSON extends AsyncTask<String, Void, Void>{
String fileName;
String responseTxt;
String inputLine;
String folder;
#Override
protected Void doInBackground(String... strings) {
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//Set methods and timeouts
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder response = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
response.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
responseTxt = response.toString();
Log.d(TAG, "doInBackground: responseText " + responseTxt);
// PREPARE FOR WRITE FILE TO DEVICE DIRECTORY
FileOutputStream fos = null;
fileName = "fileName.json";
folder = fileFolderDirectory();
try {
fos = new FileOutputStream(new File(folder + fileName));
//fos = openFileOutput(folder + fileName, MODE_PRIVATE);
fos.write(responseTxt.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null){
fos.close();
}
}
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// -- THIS METHOD IS USED TO ENSURE YOUR FILE AVAILABLE INSIDE LOCAL DIRECTORY -- //
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(folder +fileName));
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
Toast.makeText(TestActivity.this, "result " + sb.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ops, almost forget this method
public static String fileFolderDirectory() {
String folder = Environment.getExternalStorageDirectory() + File.separator + "write_your_app_name" + File.separator;
File directory = new File(folder);
if(!directory.exists()){
directory.mkdirs();
}
return folder;
}
Your root is wrong
String root = "data/data/package.appname";
make sure your root contains right package name or file path.
package name which should be your application id
Hi friends have lot of confusion.
First thing is it's not storing in on my device instead of it stores on my emulator under this path data/data/com.customfonts/files/Robotoo.ttf. Then when I try to get file throwing Runtime Exception file not found because it's searching under data/user/0/com.customfonts/Robotoo.ttf instead of searching data.data/com.customfonts/files/Robotoo.ttf.
getDirectory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
new DownloadingTask().execute();
Log.i("FilePAthFirst",""+getFilesDir());
}
});
btnGETDATA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String filename="Robotoo.ttf";
getTypeface(filename);
}
});
private Typeface getTypeface(String filename)
{
Typeface font;
try
{
font = Typeface.createFromFile(getFilesDir() +"/"+filename);
Log.i("FOnt found",""+font);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return font;
}
private class DownloadingTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL(fonturl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
FileOutputStream fos = new FileOutputStream(getApplicationContext().getFilesDir()+ "Robotoo.ttf");
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
outputFile = null;
Log.e("Error", "Download Error Exception " + e.getMessage());
}
return null;
}
}
Harmonize the code to get the file path for saving the file and loading the file.
To load the tff also use getApplicationContext().getFilesDir()+filename
I used your same code, which is in answer it working fine, May be you can check you have permission for the internet in Manifest <uses-permission android:name="android.permission.INTERNET"></uses-permission>, if you already have this, You can wait till onPostExecute of your AsyncTask and check you are getting any error.
Internal storage
And For internal storage, It will not be constant as data.data/com.customfonts/files/ from Android 6.0, It will be dynamic, We should not hard code the path(You are doing that is correct)
Refer this Offical Doc
Edited: Forgot to Add earlier that to writing a file in internal storage as per doc we should use openFileOutput so I am using that.
private class DownloadingTask extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("[your url here]");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.connect();
Log.d("sdsdfds", "doInBackground: " + getApplicationContext().getFilesDir());
FileOutputStream fos = getApplicationContext().openFileOutput("Robotoo4.ttf", MODE_PRIVATE);
Log.i("Download","complete");
Log.i("FOS",""+fos.toString());
InputStream is = c.getInputStream();
byte[] buffer = new byte[4 * 1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
File file = new File(getFilesDir() + "/" + "Robotoo4.ttf");
Log.d("", "onPostExecute: " + file.exists() + " " + file.getAbsolutePath() + " Length " + file.length() );
}
}
protected void doDownload(final String urlLink, final String fileName) {
Thread dx = new Thread() {
public void run() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/Content2/");
if(dir.exists()==false) {
dir.mkdirs();
}
//Save the path as a string value
try
{
URL url = new URL(urlLink);
Log.i("FILE_NAME", "File name is "+imageFile);
Log.i("FILE_URLLINK", "File URL is "+url);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(dir+"/"+imageFile);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{
e.printStackTrace();
Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e);
}
}
};
dx.start();
}
through this, I cannot download the file from the server.
How to solve this problem?
First of all you should use Async-Task.
Here is how you can do this
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}
I am working on the it should download the file from server and store in the sdcard .
But I getting the exception : java.io.filenotfoundexception (permission denied)
public class MainActivity extends ActionBarActivity {
// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
File file,sdcard;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
System.out.print("BAckground");
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream(); '
GEtting exception in line '
output = new FileOutputStream("sdcard/file.mp3");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
Try this
File root = new File(Environment.getExternalStorageDirectory(), "file.mp3");
if (!root.exists()) {
root.mkdirs();
}
output = new FileOutputStream(root);
and add permission on manifest file as
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try this code:
File yourFile = new File(Environment.getExternalStorageDirectory(),"yourfile.txt");
// replace yourfile.txt with "file.mp3" your file name
if(!yourFile.exists()) {
yourFile.createNewFile();
}
FileOutputStream output = new FileOutputStream(yourFile, false);
Also do not forget to add this permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You also need to check weather your sdcard is mounted or not,
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// Mounted
}
else {
}
Do like this,
File root = new File(Environment.getExternalStorageDirectory(), "file.mp3");
if (!root.exists()) {
root.mkdirs();
}
output = new FileOutputStream(root);
And add this permission in Android menfestfile.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public class PreviewDownload extends AsyncTask<String, Void, String> {
public static final String TAG = "PreviewDownload";
public String inputPath = null;
public String outputFolder = null;
public IRIssue issue = null;
#Override
protected String doInBackground(String... parms) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
issue = Broker.model.issueDataStore.getIRIssue(parms[0]);
outputFolder = IRConstant.issueFolder(issue.year, issue.month, issue.day, issue.pubKey);
try {
inputPath = IRConstant.downloadFile(issue.year, issue.month, issue.day, issue.pubKey, "preview", "0");
URL url = new URL(inputPath);
Log.d (TAG,"input: " + inputPath);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
return null;
// return "Server returned HTTP " + connection.getResponseCode()
// + " " + connection.getResponseMessage();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(outputFolder + "/preview.zip");
Log.d (TAG,"output: " + output);
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
} catch (Exception e) {
// return e.toString();
return null;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return outputFolder;
}
#Override
protected void onPostExecute(String outputFolder) {
// TODO Auto-generated method stub
super.onPostExecute(outputFolder);
if (outputFolder != null) {
File zipFile = new File (outputFolder + "/preview.zip");
if (Utils.unzip(outputFolder,outputFolder + "/preview.zip" )) {
zipFile.delete();
issue.isThumbDownloaded = 1;
} else {
issue.isThumbDownloaded = 0;
}
} else {
Toast.makeText(Broker.launcherActivity.getBaseContext(), R.string.wordCantDownload, Toast.LENGTH_LONG).show();
issue.isThumbDownloaded = 0;
}
issue.updateProgress(issue.progress);
}
}
Here is the downloader I implemented , the problem is , when the network lost, the output become null and show error message, however, if I would like to retry two times before showing error message, are there any way to do this? If I perfer not to pass in an object instead of string ,is it not recommended? thanks
What prevents you from re-instanciating and re-executing a "Downloader" from your catch blocks in case of errors ?
You could use a single common shared object between dowloader instances to count the attempts, or better, pass a parameter to each of them. In the catch block, you would then retry if you didn't reach the limit, and increase the value passed to a new downloader... Something recursive.
int expectedLength = connection.getContentLength();
can you compare with the expectedLength & downloaded length and retry?