Simply, what I want to do is downloading a file from web server. it's also known as "Socket Programming" . Python, Java , C , C++ and so forth has that network part. Mostly, Python and Java is a famous for socket programming.
I've to do it with java due to the requirements.
Okay. Let's see. it's simple .
First of all, I've created a URL
URL url = new URL("http://localhost/epub/");
Then open the URL connection and check the condition ,
URLConnection urlCon = url.openConnection();
HttpURLConnection con = null;
if (urlCon instanceof HttpURLConnection) {
con = (HttpURLConnection) urlCon;
} else {
System.out.println("Enter URL");
return;
}
Anyway, downloading files through URL is also I/O . Thus, we'd use FileOutPutStream, BufferInputStream and others. Declare a BufferInputStream first. pass the URL to it and open it.
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL("http://localhost/epub/").openStream());Create a FileOutPutStream to get the file and you can name the out coming file as you like . Define BufferOutPutStream and Buffer Size in Bytes , check the condition. Then close all connection.
java.io.FileOutputStream fos = new java.io.FileOutputStream("mgpyone");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[102400];
int x = 0;
while ((x = in.read(data, 0, 102400)) >= 0) {
bout.write(data, 0, x);
}
bout.close();
in.close();
Then, That's all. Take a look at full code.
package url;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
*
* @author yelinaung
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
URL url = new URL("http://localhost/epub/");
URLConnection urlCon = url.openConnection();
HttpURLConnection con = null;
if (urlCon instanceof HttpURLConnection) {
con = (HttpURLConnection) urlCon;
} else {
System.out.println("Enter URL");
return;
}
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL("http://localhost/epub/").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("mgpyone");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[102400];
int x = 0;
while ((x = in.read(data, 0, 102400)) >= 0) {
bout.write(data, 0, x);
}
bout.close();
in.close();
}
}
Have Fun !
0 comments:
Post a Comment