Android java unable to download file - java

am trying to download file from server , but no success my code seems to be ok
URL url = null;
URLConnection con = null;
int i;
try {
url = new URL(downlink); // url : http://10.0.2.2:800/myproject/down/file9.txt
con = url.openConnection();
String dest_path = c.getFilesDir().getPath() + "/textfile.txt"; //Download Location set to : /data/data/com.myproject.androidt/files/textfile.txt
File file = new File(dest_path);
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
FileOutputStream fos = context.openFileOutput("textfile.txt", Context.MODE_PRIVATE);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while ((i = bis.read()) != -1) {
bos.write(i);
}
bos.flush();
bis.close();
return true;
} catch (MalformedInputException malformedInputException) {
Log.d("dark","Failure : MalformedInputException occured in downloading");
// error in download
return false;
} catch (IOException ioException) {
Log.d("dark","Failure : IO Error occured in downloading");
return false;
// error in download
}
so please help i get IO exception , do not know what's wrong with code :(

I believe you have to call the openFileOutput method to get the FileOutputStream
FileOutputStream fos = openFileOutput("textfile.txt", Context.MODE_PRIVATE);
and you only need the file name not the path.

Related

Download executable file from java

I am able to download PDF,doc and other formats using below code. But when I try to download a .msi file from the URL/server location, I am unable to download it because .msi can not be converted to byte.
try {
URL url=new URL(link);
HttpURLConnection http=(HttpURLConnection)url.openConnection();
double fileSize=(double)http.getContentLengthLong();
BufferedInputStream in=new BufferedInputStream(http.getInputStream());
FileOutputStream fos = new FileOutputStream(this.out);
BufferedOutputStream bout= new BufferedOutputStream(fos,1024);
byte[] buffer= new byte[1024];
double downloaded=0.00;
int read=0;
double percentDownloaded=0.00;
while((read=in.read(buffer,0,1024)) >= 0 )
{
bout.write(buffer,0,read);
downloaded+=read;
percentDownloaded=(downloaded*100)/fileSize;
String percent=String.format("%.4f", percentDownloaded);
System.out.println("Downloaded "+percent+" of file.");
}
bout.close();
in.close();
System.out.println("Download Completed..");
}
catch(IOException ie)
{
ie.printStackTrace();
}
Can u please help me out to download .msi file from link through java ?

How to create a ZIP InputStream in Android without creating a ZIP file first?

I use NanoHTTPD as web server in my Android APP, I hope to compress some files and create a InputStream in server side, and I download the InputStream in client side using Code A.
I have read Code B at How to zip and unzip the files?, but how to create a ZIP InputStream in Android without creating a ZIP file first?
BTW, I don't think Code C is good way, because it make ZIP file first, then convert ZIP file to FileInputStream , I hope to create a ZIP InputStream directly!
Code A
private Response ActionDownloadSingleFile(InputStream fis) {
Response response = null;
response = newChunkedResponse(Response.Status.OK, "application/octet-stream",fis);
response.addHeader("Content-Disposition", "attachment; filename="+"my.zip");
return response;
}
Code B
public static void zip(String[] files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
}
finally {
origin.close();
}
}
}
finally {
out.close();
}
}
Code C
File file= new File("my.zip");
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
} catch (FileNotFoundException ex)
{
}
ZipInputStream as per the documentation ZipInputStream
ZipInputStream is an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries.
Earlier I answered to this question in a way that it is not possible using ZipInputStream. I am Sorry.
But after investing some time I found that it is possible as per the below code
It is very much obvious that since you are sending files in zip format
over the network.
//Create proper background thread pool. Not best but just for solution
new Thread(new Runnable() {
#Override
public void run() {
// Moves the current Thread into the background
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
HttpURLConnection httpURLConnection = null;
byte[] buffer = new byte[2048];
try {
//Your http connection
httpURLConnection = (HttpURLConnection) new URL("https://s3-ap-southeast-1.amazonaws.com/uploads-ap.hipchat.com/107225/1251522/SFSCjI8ZRB7FjV9/zvsd.zip").openConnection();
//Change below path to Environment.getExternalStorageDirectory() or something of your
// own by creating storage utils
File outputFilePath = new File ("/mnt/sdcard/Android/data/somedirectory/");
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(httpURLConnection.getInputStream()));
ZipEntry zipEntry = zipInputStream.getNextEntry();
int readLength;
while(zipEntry != null){
File newFile = new File(outputFilePath, zipEntry.getName());
if (!zipEntry.isDirectory()) {
FileOutputStream fos = new FileOutputStream(newFile);
while ((readLength = zipInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, readLength);
}
fos.close();
} else {
newFile.mkdirs();
}
Log.i("zip file path = ", newFile.getPath());
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
// Close Stream and disconnect HTTP connection. Move to finally
zipInputStream.closeEntry();
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
// Close Stream and disconnect HTTP connection.
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
}).start();

Insufficient System resources exist to complete the requested services

Getting the above error when trying to download large data using HttpGet
String uri = "";
getMethod = executeGet(uri);
httpClient.executeMethod(getMethod);
InputStream istream = getMethod.getResponseBodyAsStream();
byte[] data = IOUtils.toByteArray(istream);
FileUtils.writeByteArraytoFile(new File("xxx.zip"),data)
You are using a temporary byte array that might be the cause of the problem.
You can directly write the content of the stream to your file.
String uri = "";
getMethod = executeGet(uri);
httpClient.executeMethod(getMethod);
InputStream istream = getMethod.getResponseBodyAsStream();
IOUtils.copy(istream, new FileOutputStream(new File("xxx.zip"));
You're reading the entire response into the byte[] (memory). Instead, you could stream the output as you read it from istream with something like,
File f = new File("xxx.zip");
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(f));) {
int c = -1;
while ((c = istream.read()) != -1) {
os.write(c);
}
} catch (Exception e) {
e.printStackTrace();
}

How to get a binary file from a remote php script response?

I'm calling a script that gives me a binary file (12345.cl), with binary data. The script is done, and it's working, if I paste it on the navigator I get the binary file.
Now I have a problem: How I transform the response of the script into a binary resource to use it in my app?
For the moment, i have this code:
public void decodeStream( String mURL ){
BufferedInputStream bis = new BufferedInputStream(new URL(mURL).openStream(), BUFFER_IO_SIZE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(baos, BUFFER_IO_SIZE);
copy(bis, bos);
bos.flush();
Then, I have a BufferedOutputStream with the response, but I don't know how to transform it into a binary resource to use it
I need to obtain a datainputstream with the file but I don't know how to achieve it
You can use following code:
public void decodeStream( String mURL, String ofile ) throws Exception {
InputStream in = null;
FileOutputStream out = null;
try {
URL url = new URL(mURL);
URLConnection urlConn = url.openConnection();
in = urlConn.getInputStream();
out = new FileOutputStream(ofile);
int c;
byte[] b = new byte[1024];
while ((c = in.read(b)) != -1)
out.write(b, 0, c);
} finally {
if (in != null)
in.close();
if (out != null)
out.close();
}
}

How can I delete picture programmatically in Android?

I wrote some code that lets me save pictures in my data/data in Android internal storage. Now I would like to know if there is a way to delete those pictures from internal storage.
Here is what I have for saving:
public boolean saveImg( String showId ) {
try {
URL url = new URL(getImgUrl( showId ));
File file = new File(showId + ".jpg");
/* 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(PATH+file);
fos.write(baf.toByteArray());
fos.close();
return true;
} catch (IOException e) {
return false;
}
}
I tried this but it doesn't delete from data/data. Any suggestions as to what I'm doing wrong?
public void DeleteImg(String showId) {
File file = new File( PATH + showId +".jpg" );
file.delete();
}
Try this:
File file = new File(selectedFilePath);
boolean deleted = file.delete();

Categories

Resources