I am trying to download a mp3 file from a server.
I successfully made it, and I can play the file, but there is no thumbnail and file info, such as artist and album names.
When I'm downloading the file directly from chrome, the information I stated above, DOES get downloaded.
Any ideas how to get it work?
Here is my code:
URL url = new URL(urlDwn+urlVid);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();
connection.connect();
//file length
int lengthOfFile = connection.getContentLength();
//intput - read file
InputStream inputStream = new BufferedInputStream(url.openStream(), 8192);
//output - write file
if(true) {
System.out.println("Downloading");
OutputStream outputStream = new FileOutputStream(root+"/"+fileName);
System.out.println(root+"/"+fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = inputStream.read(data)) != -1) {
total += count;
//progress
publishProgress((int) ((total * 100) / lengthOfFile));
//writing to file
outputStream.write(data,0, count);
}
outputStream.flush();
outputStream.close();
inputStream.close();
I SOLVED IT!
it seems that the thumbnail and mp3 tag(artist and etc) were downloaded properly. the problem was in the file manager itself(or maybe the Android system), so when I restarted the device, it shown itself!
EDIT
There is no need to reboot. All you need to do is to add the lines below to the onPostExecute method, which tell the system that a new file has been added.
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
Related
I'm trying to handle the download of some files in my app. Basically I download a file when needed and show it to the user.
I also want to seize the downloaded files as cache, so I use a hash over the url and when the map collides with an existing file I consider it a cache hit.
My pseudo code is:
String filename = hash(url);
File outputFile = new File(cacheFolder,filename);
if(!outputFile.exists()){
download(url,outputFile);
}
return outputFile;
The code I'm using to download the file from the url is;
URL url = new URL(urlToDownload);
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(connection.getInputStream());
OutputStream output = new FileOutputStream(outputFile.getAbsolutePath());
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();
It works nice but I have a problem for detecting the following case:
The app starts downloading a file, while partially written, the user kills the app, leaving the output file in a inconsistent state.
The user reopens the app, I detect the file exists but I can't detect the file is corrupt, so I try to open the file, failing.
How can I solve this?
Should I download in a temp file and copy it to the outputFile while completed? Or this could cause a unnecessary overhead.
Is there some way to avoid the file to be created until the download is finished without using the temporally file+copy approach?
Thanks
i have a created 3 xml files and compressed into a zip folder . The folder is send from server. When i download the zip folder through browser, its working properly and can extract the files. But when i download it from android application and store in SD card, it is corrupted. I pulled the file from SD card to computer and tried to extract the folder, it shows Zip Folder is invalid . My code is given below :
DefaultHttpClient httpclient1 = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(
Configuration.URL_FEED_UPDATE);
byte[] responseByte = httpclient1.execute(httpPostRequest,
new BasicResponseHandler()).getBytes();
InputStream is = new ByteArrayInputStream(responseByte);
// ---------------------------------------------------
File file1 = new File(Environment
.getExternalStorageDirectory() + "/ast");
file1.mkdirs();
//
File outputFile = new File(file1, "ast.zip");
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
When I used
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(is));
The ZipInputStream can't store values from stream.
I'd guess that your main mistake is where you get the input stream. What you are actually doing is to get the server response as String (BasicResponseHandler) and then converting that to bytes again. Since Java is all UTF-8 this most likely does not work.
Better try something like
HttpResponse response = httpclient1.execute(httpPostRequest);
InputStream is = response.getEntity().getContent()
(And do better null pointer checking, read the content in a try-catch block and make sure you close all resources in a finally block.)
As a disclaimer, I've already seen this post and the posts linking to it.
I have a file hosted on a server that is n archived file and I am trying to unarchive it using this method. When the file is pre-downloaded to the device and I open and unarchive it in my application, through an intent-filter from Downloads, there isn't any problem. However, when I download it from the server within my application, then try to unzip it, I get the error in the title on this line:
ZipFile zipfile = new ZipFile(archive);
Where archive is a File pointing to the archive file I downloaded. The code I'm using to download the archive is as follows:
String urlPath = parameters[0], localPath = parameters[1];
try
{
URL url = new URL(urlPath);
URLConnection connection = url.openConnection();
connection.addRequestProperty("Accept-Encoding", "gzip");
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new BufferedOutputStream(new FileOutputStream(localPath));
byte data[] = new byte[1024];
long total = 0;
int count;
while((count = input.read(data)) != -1)
{
total += count;
publishProgress((int)total * 100 / fileLength);
output.write(data);
}
output.flush();
output.close();
input.close();
I've recently added the encoding type as-per the post I referenced at the top, but I am still getting the same error. Any help would be great.
Just to clarify:
I have an archive file
It unarchives fine when the file was downloaded externally and opened/unarchived inside my app
When I download the archive and then try to unarchive it, I receive the error java.util.zip.ZipException: Central Directory Entry not found
My best guess is that this is a problem with my download. However, that being said, I don't know what I'm doing wrong.
You aren't copying the download correctly. You must use
output.write(data, 0, count);
Otherwise you are writing arbitrary junk into the file.
So I have and android app where i get an audio file from a server and write the file to my sdcard:
InputStream inputStream = resp.getEntity().getContent();
File mess = new File("sdcard/Music/message"+ i +".3gp");
OutputStream out = new FileOutputStream(mess);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
inputStream.close();
out.flush();
out.close();
However when I do this my file does not appear in the play music app. how can I fix this?
Try this code:
File f = new File(Environment.getExternalStorageDirectory(),"/Music/message\"+ i +\".3gp\"") ;
I guess your downloaded file hasn't been inserted into the media provider database, and therefor won't show up in the Play Music app.
You could try triggering a rescan of the sdcard after downloading the file:
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
I've developed an application in which user can download .mp3 files from server. And pre-defined a path to mnt/sdcard/foldername for saving such files. I had run my program in HTC, LG, Samsung works perfect but when I running a same program at samsung galaxy s2 getting an issue that can't able to write(store) in mnt/sdcard/foldername and tried
Environment.getExternalStorageDirectory().getAbsolutePath()
but its shows downloaded file names in given path and zero bytes for each files properties. Any idea to solve this issue?
The SG2 does usually not have a sd-card and uses the internal flash memory as "external" storage. I have solved this issue with this code:
private File initCacheDir() {
String sdState = android.os.Environment.getExternalStorageState();
File imageCacheDir;
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdDir = android.os.Environment.getExternalStorageDirectory();
imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
}
else
imageCacheDir = context.getCacheDir();
if(!imageCacheDir.exists())
imageCacheDir.mkdirs();
return imageCacheDir;
}
Note that this code give you the location of the cache directory, which is usually located in the Android/data folder on the sd-card.
You'll find more details how to solve this issue with SG2 here:
How could i get the correct external storage on Samsung and all other devices?
try this
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
I finally found the code
public void download(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("downloaded"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Source: link