java code to download a file from server - java

using java code in windows i need to download several files from a directory placed in a server. those files in server are generated separately. so i'll not know the name of those files. is there any way to download it using JAVA and saving it in a specific folder.
i am using apache tomcat.
I read all other threads related to java file download. But none of them satisfy my requirement.

try {
// Get the directory and iterate them to get file by file...
File file = new File(fileName);
if (!file.exists()) {
context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
context.setForwardName("failure");
} else {
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition", "attachment"+
"filename=" + file.getName());
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope you got some idea...

Use java.net.URL and java.net.URLConnection classes.

Hi you can use this following code snippet to down the file directly :
URL oracle = new URL("http://www.example.com/file/download?");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Kindly refer about openStream in this [URL] : http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html

You can use HttpURLConnection to download file over HTTP, HTTPS

It is only possible if server lists directory contents. if it does, your can make an HTTP request to:
http://server:port/folder
that would give you list of files.
Once you have that, you can download individual files by parsing output if this http request.

If it is server, then the process must be like using the FTP credentials you have to dosnload the files. This java file download example may help you.

Related

Trouble downloading video file greater than 3.5mb

I'm able to successfully send, the encoded video byte[](in string) of any size, response from server, but while downloading in mobile i always encounter MemoryOutOfBoundException when the video requested exceeds 3.5mb(approx), otherwise works fine.
The code below is the one I'm currently using.
String image = (encoded byte[] in form of string from server);
byte[] byteImageData = new byte[image.length()];
byteImageData = Base64.decode(image, Base64.DEFAULT);
System.gc();
BufferedOutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(file));
out.write(byteImageData);
out.flush();
} catch (IOException e) {
e.getMessage();
}
finally {
if (out != null) {
out.close();
}
System.gc();
All I need is that the mobile should be capable enough to download atleast 20mb.
Can anyone please help me out to overcome this problem?
I would suggest to use Android's Download Manager https://developer.android.com/reference/android/app/DownloadManager.html
Then Check register for broadcast receiver to listein for file download.
Please check this example: http://blog.vogella.com/2011/06/14/android-downloadmanager-example/

Uploading a .zip file as binary InputStream from REST service

I have developed a REST Service with RESTEasy 3.0.12 deployed on WildFly 9 to upload a file in local file system.
I was trying to upload a zip file (testing with POST MAN sending file as binary not multi-part) I could successfully upload CSV, TXT, file format but when I try to send a ZIP file it saves correctly in the local file system but when I try to unzip it says
Headers error
Unconfirmed start of archive
Warnings: headers error
There are some data after the end of the payload data
Code:
#Path("/uploadZip")
#POST
#Produces(MediaType.APPLICATION_JSON)
public Response uploadZip(#Context HttpServletRequest req, InputStream payload){
// save to filesystem local.
Writer wr = null;
String tempFileName = System.getProperty("java.io.tmpdir");
try {
wr = new BufferedWriter(new FileWriter(tempFileName));
IOUtils.copy(payload, wr, "UTF-8");
} catch (IOException e) {
return errorResponse;
} finally {
// closing writer and stream
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(payload);
}
...
}
Does anyone know how to save a good zip file?
***General information on your Headers error:
Zip files contain local headers and a central directory at the end of the file. I don't know the gruesome details--and I won't attempt to expand upon them, but if you're getting a headers error then your zip file is corrupt. I'm not sure what you mean by there is some data after the "payload data."
***Thoughts on your code: Let's think conceptually.
Your endpoint is capturing an InputStream object, which is the superclass of all InputStream objects that represent an input stream of bytes. Your file is essentially wrapped in an object that you can read from byte-for-byte. The first problem I see is that you declare a Writer to write those bytes from the InputStream. Remember--Readers and Writers are for writing character streams, Input and Output streams are for byte streams. This explains why your CSV and TXT files are successful. It is important to know that difference and remember it!
#Path("/uploadZip")
#POST
#Produces(MediaType.APPLICATION_JSON)
public Response uploadZip(#Context HttpServletRequest req, InputStream payload){
OutputStream fos = new FileOutputStream(new File("path/to/filename.zip");
try {
byte[] bufferSize = new byte[1024];
int i = 0;
while ((i = payload.read(bufferSize)) != -1) {
fos.write(buf, 0, i);
}
} catch (IOException e) {
return errorResponse;
} finally {
fos.close();
}
...
}
I am confident that it will work. Let me know if this gives you any trouble. Best of luck!

retrieve single image via its url in java

I have a problem and I hope that you can help me. I would appreciate any help from anyone. The problem is the following.
I have a camera that has an http service, and I am communicating with the camera using the http. So the problem is that I send http request and I have back an http response in which I have a binary jpeg data. But I do not know how to convert that data into picture.
So my question is how can I convert that binary data into picture with java?
This is one example
http request:
GET (url to picture)
http response:
binary jpeg data
I thank to all of you in forward for all of your help.
URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
// while ((inputLine = in.readLine()) != null){
// inputLine = in.readLine();
File file = new File("D:\\alphas\\proba.bin");
boolean postoi = file.createNewFile();
FileWriter fstream = new FileWriter("D:\\alphas\\proba.bin");
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null){
out.write(in.readLine());
// out.close();
// System.out.println("File created successfully.");
System.out.println(inputLine);
}
System.out.println("File created successfully.");
out.close();
in.close();
With this code I am getting the binary JPEG data, and I menage to save the data in a file. So the question is now how to convert this data into picture, or how to create the picture?
By the way I do not need to save the file that I get, if you have a way to create the picture directly it would be the best way
retrieve single image via its url in java
you just need to write byte data of image in response and set the proper content type, It will serve image from servlet
try {
URL url = new URL("http://site.com/image.jpeg");
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Am I missing something or are you just looking for this:
new ImageIcon(new URL("http://some.link.to/your/image.jpg"));
If you need to save the data from the URL, then just read the bytes from the corresponding InputStream and write the read bytes to a FileOutputStream:

unable to read a text file from another machine

I am unable to read a text file which is there in another machine with different IP.
Below is my code. Please take a look it..
URL url =
new URL("http://10.128.0.1/d:/kiranshare/testout.txt");
br = new BufferedReader(new InputStreamReader(is));
File file=new File(url.getFile());
System.out.println(file);
System.out.println(file.getAbsolutePath());
System.out.println(file.getName()+file.getParentFile());
System.out.println("url="+file);
// InputStream is = url.openStream();
System.out.println("is"+is);
ByteArrayOutputStream os = new ByteArrayOutputStream();
System.out.println("os"+os);
byte[] buf = new byte[4096];
int n;
while ((n = is.read(buf)) >= 0)
os.write(buf, 0, n);
os.close();
is.close();
byte[] data = os.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please suggest me where I am doing wrong???
Thanks in Advance
Please check the url that you are passing new URL("http://10.128.82.93/d:/kiranshare/testout.txt");
i think it should be something like new URL("\\10.128.82.93\kiranshare\testout.txt");
if the file is hosted on a web server , try opening first it from the browser and see if the link is correct.
You should not use HTTP protocol and URL class. Share the folder and directly use the shared folder path to read the file using File class.
For example you can say
java.io.File myFile = new java.io.File("\\\\10.128.0.1\\kiranshare\\testout.txt");
and then you can use BufferedReader to read the file. Make sure that you have sufficient privileges to read that file.

Java and FTP to edit online text files

In my Java swing program, I read, edit and save various text files in a local folder using Scanner and BufferedWriter. Is there an easy way I can keep my current code, but, using FTP, edit a web file rather than a local file? Thanks everyone.
You can use the URL and URLConnection classes to obtain InputStreams and OutputStreams to files located on an FTP Server.
To read a file
URL url = new URL("ftp://user:pass#my.ftphost.com/myfile.txt");
InputStream in = url.openStream();
to write a file
URL url = new URL("ftp://user:pass#my.ftphost.com/myfile.txt");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
I tried to achieve the same and the answers to those questions helped me a lot:
Adding characters to beginning and end of InputStream in Java (the one marked as right shows how to add a custom string to the InputStream)
Uploading a file to a FTP server from android phone? (the one from Kumar Vivek Mitra shows how to upload a file)
I added new text to the end of my online file like this:
FTPClient con = null;
try {
con = new FTPClient();
con.connect(Hostname);
if (con.login(FTPUsername, FTPPassword)) {
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
InputStream onlineDataIS = urlOfOnlineFile.openStream();
String end = "\nteeeeeeeeeeeeeeeeest";
List<InputStream> streams = Arrays.asList(
onlineDataIS,
new ByteArrayInputStream(end.getBytes()));
InputStream resultIS = new SequenceInputStream(Collections.enumeration(streams));
// Stores a file on the server using the given name and taking input from the given InputStream.
boolean result = con.storeFile(PathOfTargetFile, resultIS);
onlineDataIS.close();
resultIS.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
return "Writing successful";
} catch (IOException e) {
// some smart error handling
}
Hope that helps.

Categories