unable to download the file using java - java

I've just implemented a jsp program to upload a file into my PC folder. The path of this folder is E:\UploadedFile. The file name i want to download is assad.xml (the one i have just uploaded). This is how i am trying to download it. Please check my code and correct me if i am wrong.
<%#page import="java.io.*,java.net.*"%>
<%
System.setProperty("http.proxyHost", "192.168.1.10");
System.setProperty("http.proxyPort", "8080");
try {
/*
* Get a connection to the URL and start up
* a buffered reader.
*/
long startTime = System.currentTimeMillis();
System.out.println("Connecting to URL...\n");
URL url = new URL("E://UploadedFiles/");
url.openConnection();
InputStream reader = url.openStream();
/*
* Setup a buffered file writer to write
* out what we read from the website.
*/
FileOutputStream writer = new FileOutputStream("E:/assad.xml");
byte[] buffer = new byte[153600]; // Buffer for 150K blocks at a time
int totalBytesRead = 0;
int bytesRead = 0;
System.out.println("Reading ZIP file 150KB blocks at a time.\n");
while ((bytesRead = reader.read(buffer)) > 0){
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
totalBytesRead += bytesRead;
}
long endTime = System.currentTimeMillis();
System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes
read (" +
(new Long(endTime - startTime).toString())+ " millseconds).\n");
writer.close();
reader.close();
}catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
%>
The name of the folder in which i have just uploaded my file is UploadedFiles and its in E: drive. The name of the file i want to download is assad.xml. Its available inside this folder.

Probably you inverted the filename, like Renjith said. For a more consistent API take a look at: http://hc.apache.org/httpcomponents-core-ga/index.html

Related

Java get Blob from Database and write

I've got a Table where i store my pdf files as blob.
I get the InputStream and insert it like this.
pstmt.setBinaryStream(1, inputStream);
For this I created a Model with Integer ID and InputStream blob; as variables.
I read the blob like this out of my DB.
blob.setBlob(rs.getBinaryStream("blob_file"));
Now I tried to create the PDF file again with this.
byte[] buffer = new byte[4096];
File file= new File("c:\\MyPath\\myPDF.pdf");
try{
FileOutputStream output= new FileOutputStream(file);
int b = 0;
while ((b = blob.getBlob().read()) != -1) {
output.write(buffer);
}
output.close();
}catch(IOException ex){
System.err.println("Blob Error: " + ex.getMessage());
}
With this method I get a corrupt PDF file which I can't open.
I found an alternative which worked very well like this.
IOUtils.copy(blob.getBlob(), output);
But I don't get why my first Version didn't work and what's the difference between These two.
Try this:
FileOutputStream output = null;
InputStream is = blob.getBlob();
try{
output= new FileOutputStream(file);
int b = 0;
while ((b = is.read(buffer)) != -1) {
output.write(buffer, 0, b);
}
} catch(IOException ex){
System.err.println("Blob Error: " + ex.getMessage());
} finally {
is.close();
if (output != null) {
output.close();
}
}
The problem in your initial code is the fact that you don't use the value of b (which is the the total number of bytes read into the buffer) so you probably write more bytes than you should which is probably the cause of the corruption of your file.

SmbFileOutputStream write creating corrupted jpg files

I'm using JCIFS SmbFileOutputStream write to upload jpg (and mp4) files to a share on a local Windows network. While this works well most of the time, I sometimes find that the resulting files are corrupt - e.g. if it's a jpg perhaps only the top part of the photo will be legible/visible.
I have the upload in a try/catch block, but it is not throwing an exception. Is there any way that I can verify that a file has been uploaded correctly?
try {
if (debugging_on) {
logger.info("UploadService.011 UploadFiles: uploading file:" + destFileName);
}
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
FileInputStream fileInputStream = new FileInputStream(new File(
sSourceFilePath));
byte[] buf = new byte[16 * 1024 * 1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
sfos.write(buf, 0, len);
}
fileInputStream.close();
sfos.close();
// Update the database to include the date/time of this upload
millisStart = Calendar.getInstance().getTimeInMillis();
sql = "UPDATE upload_history SET file_uploaded_date = "
+ millisStart + " WHERE filename = '" + filename + "'";
db.execSQL(sql);
} catch (Exception e) {
mNotifyBuilder.setContentText("Upload error - check folder permissions");
mNotificationManager.notify(1, mNotifyBuilder.build());
return "WriteFailure";
sfos.close();
needs to go before
fileInputStream.close();
Close the output before you close the input,
Adding 'sfos.flush()' couldn't hurt.

How to download multiple files from a single hyperlink

I am working on a task where I need to download multiple files from a single hyperlink. When I call the one API link I want it to return multiple files.
My current code is only downloading a single file:
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
check this site . It downloads multiple files and shows its content on your screen

Java Connecting URL and downloading a zip but when extracting the zip it's not properly downloaded

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();
}

How to download a dat file from a weblink into a path in SDcard in my Android app?

In the app im developing i'l have to download a dat file along with a xml file from a webserver link.
There was no problem in downloading the xml but while downloading dat file it is throwing exception.How can i over come this state.Thank you guys..
Exception
02-01 16:33:34.713: W/System.err(1404): java.io.FileNotFoundException: http://www.myingage.com/bkpdrctry/dontwo.dat
02-01 16:33:34.723: W/System.err(1404): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:1162)
The actual code is below
protected static void downloadFile(String stringUrl, String path){
try {
URL url = new URL(stringUrl);
DebugLog.LOGD("URL " +url );
//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();
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,path);
DebugLog.LOGD("download to sd card " +url );
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
DebugLog.LOGD("File written successfully in " +path );
//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;
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The above function is called here:
downloadFile("http://www.myingage.com/bkpdrctry/dontwo.xml","/Test/dontwo.xml");
downloadFile("http://www.myingage.com/bkpdrctry/dontwo.dat","/Test/dontwo.dat");
Open http://www.myingage.com/bkpdrctry/dontwo.dat on your browser.
Throws HTTP 404.

Categories

Resources