Downloading a file from the internet - java

I am trying to download an MP3 file from the internet to an SD card in Android.
I know the desktop Java equivalent, but because I want to take advantage of some interesting looking Android based SDKs so I decided to try my hand at writing a mobile app.
Was a lot to learn, and I feel like I skipped a lot of steps.
I did something like this in Java:
File outputSong = new File("outputFolder/testSong.mp3");
is1 = new URL(currentSong).openStream();
ReadableByteChannel rbc = Channels.newChannel(is1);
FileOutputStream fos = new FileOutputStream(outputSong);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
But Android didn't like that. I looked here, the developer.android website, and some internet tutorials on how to deal with files. I tried doing this:
String currentSong = "http://nyan.90g.org/e/1/50/9f755b639fa518e7f5580b648c7b2f60.mp3";
String currentArtwork = "http://moefou.90g.org/wiki_cover/000/00/29/000002938.jpg";
String fileName = "";
URLConnection conn = new URL(currentArtwork).openConnection();
conn.setUseCaches(false);
int lastSlash = conn.getURL().toString().lastIndexOf('/');
if (lastSlash>=0)
fileName = conn.getURL().toString().substring(lastSlash+1);
if (fileName.equals(""))
fileName = conn.getURL().hashCode() + ".jpg";
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
File outputArtwork = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
FileOutputStream fos = new FileOutputStream(outputArtwork);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] data = new byte[8192];
int bytesRead = 0;
while((bytesRead = bis.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, bytesRead);
}
bos.close();
bis.close();
I got it to work ONCE, and now I've been unsuccessful in trying to repeat the action. I got the manifest permissions in. I would be grateful if anybody could show me how they would go about this.
While I'm at it, everyone says to use logcat. Is that like printing to the console? That would be helpful.

Related

Android: Corrupted characters in PDF

I'm using HttpURLConnection to get a PDF file from the server then saving that PDF to the user's phone. Getting the file is working perfectly, but when saving, some files contain corrupted characters.
InputStream in = null;
OutputStream fileOutput = null;
try {
File file = new File(path);
file.mkdirs();
file = new File(path + File.separator + fileName + "." + fileExentsion);
file.createNewFile();
fileOutput = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int read;
in = conn.getInputStream();
while ((read = in.read(buffer)) != -1) {
fileOutput.write(buffer, 0, read);
}
fileOutput.flush();
return Uri.fromFile(file).toString(); // To open an intent in onPostExecute()
}
I tried using BufferedReader and BufferedWriter but the OS couldn't open the file after being saved. It is really weird because the same strings appears in other files correctly. And when downloading the file from a desktop, it looks good too.

android : Zip Folder is invalid

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.)

Android: Issue in downloading to SD

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

Create pdf through java.io

I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();

Moving database on Android

I am shipping my Android application with an SQLite database (300 KB), and after what I read I need to move it in order to use it. In iOS you move the database from the app to the documents folder because you can't write to the app because it is signed. Is this the reason on Android as well? So back to my question. The following code does not copy the database correctly, it only copies some of it. Why so? Have I done something wrong here.
private final static String DB_NAME = "klb.sqlite";
dbPath = "/data/data/" + context.getPackageName() + "/databases/"; // setting this in constructor
(The lines above is private members, applies to both code examples below)
BufferedInputStream bis = new BufferedInputStream(context.getAssets().open(DB_NAME));
FileOutputStream fos = new FileOutputStream(dbPath + DB_NAME);
while (bis.read() != -1) {
fos.write(bis.read());
}
bis.close();
fos.flush();
fos.close();
However this works: (Sorry for being lazy about re-indenting)
InputStream inputStream = context.getAssets().open("klb.sqlite");
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
while (bis.read() != -1) {
fos.write(bis.read());
}
Look at that closely. Your calling read twice, but write once. You're effectively skipping every other byte.

Categories