In my app, I am downloading some files. It gets automatically saved in data/data/project/files folder. Below code is used for that purpose.
URL url = new URL(audioUrl);
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[inputStream.available()];
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
int j;
while((j = inputStream.read(buffer))!=-1)
{
fos.write(buffer, 0, j);
}
fos.close();
What I require is: before adding anything to this folder i want to clear all files if any are present. How can I do that? Please reply. Thanks in advance.
I got it done by giving:
String[] allFiles = fileList();
for(int k = 0 ; k < allFiles.length; k++) {
deleteFile(allFiles[k]);
}
Related
I want to install the update automatically as my APK is not on the Play store. So I tried the following:
I followed all the steps given in
http://www.wepstech.com/download-and-install-app-programmatically/
Below is the Async Task: (URL given is correct)
URL url = new URL(arg0[0]);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int lenghtOfFile = c.getContentLength();
String PATH = Objects.requireNonNull(mContext.getExternalFilesDir(null)).getAbsolutePath();
File file = new File(PATH);
boolean isCreate = file.mkdirs();
File outputFile = new File(file, "my_apk.apk");
if (outputFile.exists()) {
boolean isDelete = outputFile.delete();
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1;
long total = 0;
while ((len1 = is.read(buffer)) != -1) {
total += len1;
fos.write(buffer, 0, len1);
publishProgress((int) ((total * 100) / lenghtOfFile));
}
fos.close();
is.close();
if (mPDialog != null)
mPDialog.dismiss()
;
I have an API checking the version and if the version is old I have given a button to download and install, So when I do that the apk is getting downloaded only (but not a full-size file) I see only 189bytes. The Async just closes thinking the file has downloaded it starts to install and when it does it gives "There was a problem parsing the package".
It is because the APK file not downloaded fully.
I am not sure why the file is not getting downloaded fully. It is an 8MB file. And I am running Android 11.
you can use the lib fetch, it's a best file downloader library for android
https://github.com/tonyofrancis/Fetch
I Want to download text file from server in private folder, that should not be accessible to user. In short I want to store that file in Application Folder only, not on memory card/internal memory. Once download complete I would like to show the text file in text view. If the file is already downloaded or present in folder, then just want to show that file contents. Can someone help me please? Thanks in Advance.
Here is the code -
url = new URL("https://tmpfiles.org/dl/11433/baby_shark_dodo.txt");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.connect();
connection.setRequestMethod("GET");
try {
File mydir = getApplicationContext().getDir("Songs", Context.MODE_PRIVATE);
if(!mydir.exists()){
mydir.mkdir();
}
final File file = new File(mydir,"Test.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
connection.disconnect();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I am downloading HTML file from server using URLConnection but I am getting FileNotFoundException. My path is correct. Using same code same file is downloaded on android of API level 25 but on API level less than it is not downloading. Also connection.getContentLength(); is giving 311 value always. I am not getting any answer to solve this. I am hereby adding my code.
My class file code is
String HomeScreenResourcefilename = WebHomescreenResObj.getString("FileName");
int ProductTargetID = WebHomescreenResObj.getInt("ProductTargetID");
String WebURL_Part1 = context.getResources().getString(R.string.FileDownloadRootPath)+"/ExhibitorData/";
String WebURL_Part2 = GlobalVariables.tradeShowName+" - "+GlobalVariables.exhibitorName+"/HTMLHomeScreen/"+ProductTargetID +"/"+HomeScreenResourcefilename;
String WebURL = WebURL_Part1 + WebURL_Part2;
try {
URL url = new URL(WebURL);
File file = new File(context.getFilesDir(), HomeScreenResourcefilename);
URLConnection connection = url.openConnection();
connection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
//Stream used for reading the data from the internet
InputStream inputStream = connection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
} catch (Exception e1) {
e1.printStackTrace();
LogE("error in 14 :"+e1);
}
Use HttpURLConnection and then connection.getResponseCode() to get the status code. If it is greater than 400, that might be the reason.
Update: Use url encoding.
i m making an android app to download pdf files from android and then saving them in a folder in internal or external memory.but sometime due to bad internet connection download stops without finshing .like file size is 1.1mb and its only downloaded upto 750kb. now the problem is whether file fully download or not my app showing it as download but in real it is not.so i want to know the exact size of file befor and after download so that i can found whether file is completely download or not.and want to restart the download.
can anybody help me........
my code
String DownloadUrl = "http://www.example.com/books/"+book_name;
String fileName = book_name;
URL url = new URL(DownloadUrl);
//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();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
// File SDCardRoot = new File("/storage/emulated/0/documents/docx/stuff/");
File SDCardRoot = new File(Environment.getExternalStorageDirectory()+File.separator+"MybookStore/paper/paperStuff/documents/docx/other/stuff/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,fileName);
String file_size = Long.toString(file.length()/1024);
int size_file=Integer.parseInt(file_size);
//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();
//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);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
my code
Any reasonable server response header will include a Content-Length key, which will hopefully denote the full length of the resource you’re trying to download.
With that in mind, here's a quick example:
HttpURLConnection connection = null;
InputStream input = null;
OutputStream output = null;
try {
final URL url = new URL(resourceUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
final int length = connection.getContentLength();
int downloaded = 0;
input = url.openStream();
output = new FileOutputStream(targetFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
downloaded += read;
}
if (downloaded == length) {
// The file was successfully downloaded.
} else {
// The file was not fully downloaded.
}
} catch (IOException e) {
// Handle exception.
} finally {
// Close resources.
}
private void doFileDownload() throws Exception {
BufferedInputStream in = null;
BufferedOutputStream out = null;
String url = "http://www.jimsonmok.com/server/uploads/"; //input
String file = "/sdcard/Shek Kip Mei MTR Station Exit A.3gp"; //output
try{
url += URLEncoder.encode("Shek Kip Mei MTR Station Exit A.3gp");
URL download = new URL(url);
URLConnection downloadConnection = download.openConnection(); //set up connection
in = new BufferedInputStream(downloadConnection.getInputStream());
out = new BufferedOutputStream(new FileOutputStream(file));
int contentlength = downloadConnection.getContentLength(); //getting the length of the file
for(int counter=0;counter < contentlength;counter++) //storing the binary I/O file
out.write(in.read());
}catch(IOException e){
}
in.close();
out.close();
}
I am trying to download an audio from the server using an android phone.
The code above I am using does not work in android.
Does anyone know the reasons?
Thanks a lot!