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 ?
Related
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();
I am downloading a few .gz file from an FTP server and un-compressing the file to read the data. I am getting the following error.
java.io.IOException: Corrupt GZIP trailer
at java.util.zip.GZIPInputStream.readTrailer(GZIPInputStream.java:200)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:92)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at com.omnesys.xdk.ClsXDKRTWeb.UnGunZip(ClsXDKRTWeb.java:961)
at com.omnesys.xdk.ClsXDKRTWeb.DeCompress(ClsXDKRTWeb.java:857)
at com.omnesys.xdk.ClsXDKRTWeb.FTPDownloadProcess(ClsXDKRTWeb.java:629)
at com.omnesys.xdk.ClsXDKRTWeb.ProcessRequestXML(ClsXDKRTWeb.java:460)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.as.ee.component.ManagedReferenceMethodInterceptorFactory$ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptorFactory.java:72)
The code for the fTP download and un compressing is as follows.
FTPClient ftp;
FTPClientConfig config;
ftp = new FTPClient();
config = new FTPClientConfig();
ftp.configure(config);
ftp.connect(strFTPServername);
ftp.user(strFTPUserName);
ftp.pass(strFTPUserPwd);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
OutputStream local = new BufferedOutputStream(new FileOutputStream(strCmnDwnldPath));
ftp.retrieveFile(strSrcFilePath, local);
local.close();
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
ftp.disconnect();
return false;
} else {
ftp.logout()
}
private boolean UnGunZip(String filename, String outputFolder) {
byte[] buffer = new byte[1024];
try {
String sfilename = new File(filename).getName();
sfilename = sfilename.substring(0, sfilename.indexOf(".gz"));
FileInputStream fileIn = new FileInputStream(filename);
GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);
FileOutputStream fileOutputStream = new FileOutputStream(outputFolder + File.separator + sfilename);
int count;
while ((count = gZIPInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
gZIPInputStream.close();
fileOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
return true;
}
My application runs in Linux environment. When i try to extract the file in the windows environment i get the error saying the file is broken.
When I try to download the same file from windows environment I don't face this issue.
Can someone help me fix this.
[EDIT:] i found this question, according to this the file should be uploaded as ASCII and downloaded as ASCII. But how do i find out if the file was uploaded using ASCII transfer?
Try to remove the "BufferedOutputStream"
OutputStream local = new BufferedOutputStream(new FileOutputStream(strCmnDwnldPath));
This should be enough:
OutputStream local = new FileOutputStream(strCmnDwnldPath);
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.
I am sending a request XML to the URL and receiving a zip file to the given path.
Sometimes I'm facing troubles when the bandwidth is low this zip file, most likely 120MB size is not getting downloaded properly. And getting an error when extracting the zip file. Extracting happens from the code as well. When I download in high bandwidth this file gets download without issue.
I'm looking for a solution without making the bandwidth high, from program level are there any ways to download this zip file, may be part by part or something like that? Or anyother solution that you all are having is highly appreciated.
Downloading :
url = new URL(_URL);
sc = (HttpURLConnection) url.openConnection();
sc.setDoInput(true);
sc.setDoOutput(true);
sc.setRequestMethod("POST");
sc.connect();
OutputStream mOstr = sc.getOutputStream();
mOstr.write(request.getBytes());
InputStream in = sc.getInputStream();
FileOutputStream out = new FileOutputStream(path);
int count;
byte[] buffer = new byte[86384];
while ((count = in.read(buffer,0,buffer.length)) > 0)
out.write(buffer, 0, count);
out.close();
Extracting :
try {
ZipFile zipFile = new ZipFile(path+zFile);
Enumeration<?> enu = zipFile.entries();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = path+"/data_FILES/"+zipEntry.getName();
long size = zipEntry.getSize();
long compressedSize = zipEntry.getCompressedSize();
System.out.printf("name: %-20s | size: %6d | compressed size: %6d\n", name, size, compressedSize);
File file = new File(name);
if (name.endsWith("/")) {
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
InputStream is = zipFile.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[86384];
int length;
while ((length = is.read(bytes)) >= 0) {
fos.write(bytes, 0, length);
}
is.close();
fos.close();
}
zipFile.close();
} catch (Exception e) {
log("Error in extracting zip file ");
e.printStackTrace();
}
I am using following code to copy icons which are available in resource folder of Plug-in "A" to a local folder. This works absolutely fine. Now I want to know if there is way to copy icons from resource folder of other plugin say (plugin B). I have to retain the copy logic in plugin A only. Is there a way to access the resource folder of other plugin from current plug-in ?
File objectDir = new File(directory + "/icons/");
if (!objectDir.exists()) {
objectDir.mkdirs();
}
InputStream inStream = null;
OutputStream outStream = null;
try {
File bfile = new File(directory + "/icons/validation.png");
inStream = this.getClass().getClassLoader().getResourceAsStream("/icons/viewAsHTML.png");
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
You should be able to get at a resource in another plugin by using the platform:/plugin/ mechanism:
url = new URL("platform:/plugin/your.plugin.package.pluginB/icons/validation.png");
InputStream inputStream = url.openConnection().getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));