download file java 11 code example

Example 1: java download file from url

try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream());  FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)) {    byte dataBuffer[] = new byte[1024];    int bytesRead;    while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {        fileOutputStream.write(dataBuffer, 0, bytesRead);    }} catch (IOException e) {    // handle exception}

Example 2: java download file from url

InputStream in = new URL(FILE_URL).openStream();Files.copy(in, Paths.get(FILE_NAME), StandardCopyOption.REPLACE_EXISTING);

Example 3: java download file from url to string

public static String URLReader(URL url) throws IOException {
    StringBuilder sb = new StringBuilder();
    String line;
 
    InputStream in = url.openStream();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        while ((line = reader.readLine()) != null) {
            sb.append(line).append(System.lineSeparator());
        }
    } finally {
        in.close();
    }
 
    return sb.toString();
}

Tags:

Java Example