java get file from url

java get file from url

To get a file from a URL in Java, you can use the URL and URLConnection classes from the java.net package. These classes provide methods for working with URLs and establishing connections to resources on the internet.

Here's an example of how to use the URL and URLConnection classes to get a file from a URL:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class Main {
  public static void main(String[] args) throws Exception {
    URL url = new URL("https://www.example.com/files/example.txt");
    URLConnection connection = url.openConnection();
    BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
    FileOutputStream out = new FileOutputStream("example.txt");
    byte[] buffer = new byte[1024];
    int length;
    while ((length = in.read(buffer, 0, 1024)) > 0) {
      out.write(buffer, 0, length);
    }
    in.close();
    out.close();
  }
}
Source‮l.www:‬autturi.com

In this example, a URL object is created from the URL of the file. The openConnection() method of the URL object is called to get a URLConnection object. The getInputStream() method of the URLConnection object is called to get an input stream of the file. A BufferedInputStream is then created from the input stream to read the file in chunks. A FileOutputStream is created to write the file to the local filesystem. The file is then read from the input stream and written to the output stream in chunks using a buffer. Finally, the input stream and output stream are closed.

You can use the URL and URLConnection classes to download any type of file from a URL, as long as the URL points to a valid resource and you have permission to access it.

Created Time:2017-11-03 22:21:10  Author:lautturi