0

Consider the following.

val br = new BufferedReader(new FileReader(inputFileName))

But instead of a file, I want to read a file directly from the web, that is, from ftp or http. So, what would be the equivalent for reading from a URL?

pythonic
  • 19,309
  • 37
  • 124
  • 208

2 Answers2

4

It's URLConnection.

Here's an example from Java documentation : Reading from and Writing to a URLConnection :

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}
Mickael
  • 4,294
  • 2
  • 29
  • 39
1

you can use java.io.InputStream

import java.net.; import java.io.;

public class URLConnectionReader { 
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    } 
} 

for more info see Reading Directly from a URL

humazed
  • 70,785
  • 32
  • 93
  • 133